3

我试图弄清楚如何在 C# 中创建一个与协议无关的套接字侦听器——它应该获取 IPv4 和 IPv6 请求。我在 Google 上可以找到的所有内容似乎都是 C。尝试类似于我在 C 中看到的内容,我尝试了以下代码:

/*Socket*/ m_sock = null;
/*IPAddress*/ m_addr = null;
/*int*/ m_port = port; /*port passed to function*/
/*int*/ m_listenqueue = listen_queue_size; /*also passed to function, number of pending requests to allow before busy*/
IPAddress[] addrs = Dns.GetHostEntry("localhost").AddressList;
if(family == null) m_addr = addrs[0];
else
{
    foreach(IPAddress ia in addrs)
    {
        if(ia.AddressFamily == family) /*desired address family also passed as an argument*/
        {
            m_addr = ia;
            break;
        }
    }
}
if(m_addr == null) throw new Exception(this.GetType().ToString() + ".@CONSTRUCTOR@: Listener Initailization Error, couldn't get a host entry for 'localhost' with an address family of " + family.ToString());

m_sock = new Socket(m_addr.AddressFamily, SocketType.Stream, ProtocolType.IP);
/*START "AGNOSTICATION LOGIC"... Tried here...*/
if(m_addr.AddressFamily == AddressFamily.InterNetworkV6) //allow IP4 compatibility
{
    m_sock.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.AcceptConnection, true);
    /*fails*/ m_sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AcceptConnection, true);
    /*fails*/ m_sock.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AcceptConnection, true);
}
/*END "AGNOSTICATION LOGIC" */
IPEndPoint _endpoint = new IPEndPoint(m_addr, m_port);
m_sock.Bind(_endpoint);
/*... tried here*/
m_sock.Listen(m_listenqueue);
/*... and tried here*/

我已经在标记的三个地方尝试了逻辑,无论我把它放在哪里,列出的两行都会抛出一个无效的参数异常。

谁能向我推荐我应该如何制作一个同时监听 IPv4/IPv6 的套接字?

4

1 回答 1

6

您可以使用 sock.SetSockOption(SocketOptionLevel.IPv6, SocketOptionName.IPV6Only, 0); 将套接字设置为允许与 IPv6 以外的其他协议的连接。它将从 Vista 开始工作。

SocketOptionName 文档

于 2013-01-28T19:49:37.357 回答