UDP Sending a multicast message and listening for a response gives a SocketException

I am sending a UDP multicast to find specific devices on the network. Then I listen to the response on port 5001.

My workflow is as follows:

  • Send the "find" multicast message to the local subnet.
  • Any wiznet devices on the network respond with the information package I want to receive

Everything works fine on Windows XP, but on Windows 7 I get a SocketException: *

Usually only one socket address is allowed (protocol / network address / port)

Strike>

I see that the multicast message goes to Wireshark and I see the response from the device (s), but my code is not responding. My code is as follows:

  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 tried various ways to structure this code. It seems that the problem is with sending and receiving on different UdpClients. My exception was caused by the creation of UdpClient immediately after opening one for sending - adding a delay between sending and receiving is fixed.

I changed my code to use the same UdpClient for sending and receiving, but I still do not receive anything when receiving.

+3
source share
1 answer

! , Sendpacket "udpclient.connect", , connect.

+2

All Articles