C#UDP套接字绑定异常

时间:2010-11-09 23:22:21

标签: c# .net sockets mesh udpclient

在有人要求之前,我已经在这个网站上看了很多,并且谷歌广泛地寻找答案无济于事。

我正在尝试为无线网格创建一个程序(adhoc除了名称之外)。大多数网络将处理TCP消息传递,但要确定所有邻居IP(因为它们在启动时将是未知的),我选择使用UDP广播作为初始发现消息。大多数情况下,该代码无关紧要,因为初始测试似乎有效,目前我不称之为。

以下是接收和注册邻居IP的部分。

protected override void ReceiveMessageUDP()
    {
        while (live)
        {
            try
            {
                UdpListener = new UdpClient(_PORTRECEIVE);
                UdpListener.EnableBroadcast = true;
                Socket socket = UdpListener.Client;
                IPEndPoint endPoint1 = new IPEndPoint(IPAddress.Loopback, _PORTRECEIVE);
                IPEndPoint endPoint2 = new IPEndPoint(IPAddress.Any, _PORTRECEIVE);
                socket.Bind(endPoint2);
                socket.Listen(25);
                Socket connected = socket.Accept();
                byte[] buffer = new byte[1024];
                int length = connected.Receive(buffer);

                IPAddress remoteIP = ((IPEndPoint)connected.RemoteEndPoint).Address;
                if (!ipAddresses.Contains(remoteIP))
                    ipAddresses.Add(remoteIP);

                Message.Add(Encoding.ASCII.GetString(buffer, 0, length));
            }
            catch (SocketException e) { Console.WriteLine(e.ErrorCode); }
            catch (Exception) { }
        }
    }

我已经使用两个IPEndPoints进行了测试,无论我如何设置它,Bind都失败了SocketException.ErrorCode 10022 Windows Socket Error Codes。这是一个无效的参数,但我很困惑这意味着所需的参数是一个EndPoint。

这在第一次运行时失败,所以它不像我试图重新绑定端口。

2 个答案:

答案 0 :(得分:1)

在构建端口时,您已将端口绑定到UdpCLient。然后,您无法将同一端口绑定到单独的IPEndPoint

UdpListener = new UdpClient(_PORTRECEIVE);  // binds port to UDP client
...
IPEndPoint endPoint2 = new IPEndPoint(IPAddress.Any, _PORTRECEIVE);
socket.Bind(endPoint2);  // attempts to bind same port to end point

如果您想这样做,请构建并绑定IPEndPoint,然后使用它而不是端口构建UdpClient

IPEndPoint endPoint2 = new IPEndPoint(IPAddress.Any, _PORTRECEIVE);
socket.Bind(endPoint2);  // bind port to end point

UdpListener = new UdpClient(endPoint2);  // binds port to UDP client via endpoint

我不确定您为何也在同一端口上设置另一个端点endPoint1。如果您尝试使用此功能,那么这可能会导致问题。

答案 1 :(得分:1)

我同意史蒂夫。但是,你说明了

  

“UDP不允许绑定或填充。”

但确实如此。您可以将任何套接字(udp或不是udp)绑定到任何网络接口。史蒂夫提示要实现它。我就是这样做的:

LocalEP = new IPEndPoint(<local IP>, _PORTRECEIVE) ;
listener = New UdpClient(LocalEP) ;

正如史蒂夫所指出的,一旦UdpClient被实例化,它就不允许重新绑定到另一个接口。诀窍是告诉构造函数事先绑定到你想要的de接口。替换为您要使用的本地接口的IP地址。

当然,这只有在您拥有(或可能拥有)多个网络接口并希望使用特定网络接口时才有用。否则,我已经看到具有有效的Internet网关的接口通常是客户端默认绑定的接口。这通常是正确的。

罗伯特