我正在试图弄清楚如何在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的套接字吗?
答案 0 :(得分:5)
你可以使用sock.SetSockOption(SocketOptionLevel.IPv6,SocketOptionName.IPV6Only,0);设置套接字以允许与IPv6之外的其他协议进行连接。它将从Vista开始工作。