I am attempting to create a program for a wireless mesh (adhoc in all but name). Most of the network will deal with TCP messaging but to determine all neighbor IPs (as they will be unknown on startup), I choose to use UDP Broadcast for the initial discovery messages. That code, for the most part, is irrelevant as initial testing appeared to work and currently I do not call it.
The following is the section to receive and register the neighbors' IPs.
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) { }
}
}
I have tested with both IPEndPoints and regardless of how I set it up, the Bind fails with SocketException.ErrorCode 10022 Windows Socket Error Codes. It is an invalid argument but I am confused about what that means as the argument required is an EndPoint.
This fails on the first run so it's not like I am attempting to rebind the port.