gpt4 book ai didi

C# IPv4/IPv6 不可知套接字监听器

转载 作者:行者123 更新时间:2023-12-03 11:50:41 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何在 C# 中创建一个与协议(protocol)无关的套接字监听器 - 它应该获取 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 的套接字吗?

最佳答案

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

SocketOptionName documentation

关于C# IPv4/IPv6 不可知套接字监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14569257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com