I'm sending a UDP multicast message to find certain devices on the network. I then listen for a response on port 5001.
My workflow is as follows:
- Send a multicast "find" message to the local subnet.
- Any wiznet devices on the network respond with an info packet which I want to receive
It all works fine on Windows XP, but on Windows 7, I get an exception of type SocketException: *
Only one usage of each socket address (protocol/network address/port) is normally permitted
I can see the multicast message go out in Wireshark, and I see the response from the device(s), but my code doesn't respond. My code looks like this:
public void StartListen()
{
SendFind();
try {
IPEndPoint localEp = new IPEndPoint(IPAddress.Any, 0);
UdpClient listenClient = new UdpClient(5001);
UdpState s = new UdpState();
s.endpoint = localEp;
s.client = listenClient;
//allow time for the find to work - aka clutching at straws
Thread.Sleep(500);
while (listenClient.Available > 0)
{
listenClient.BeginReceive(ReceiveCallback, s);
Thread.Sleep(500);
}
}
catch (SocketException e)
{
Trace.WriteLine("Could not bind to socket on " + _localPort);
}
listenClient.Close();
}
.. and RecieveCallBack ..
private void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).client;
IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).endpoint;
Byte[] receiveBytes = u.EndReceive(ar, ref e);
rxByteList.Add(receiveBytes);
messageRxed = true;
}
** UPDATE **
So I have tried various ways of structuring this code. It seems that the problem is related to sending and receiving on different UdpClients. My exception was caused by creating a UdpClient to recieve immediately after opening one to send - adding a delay between the send and receive fixed this.
I have altered my code to use the same UdpClient for the send and receive, but I'm still not getting anything on the receive.