0
votes

I am trying to receive the UPnP NOTIFY Messages from UPnP Devices in my Network. But when i send the M-SEARCH Message, i sometimes get no Answers. My Code looks like this:

public bool StartListener()
{
  if (this.ssdpSocket == null)
  {
    IPAddress localIpAddress = IPAddress.Any; 
    IPEndPoint localIpEndpoint = new IPEndPoint(localIpAddress, SsdpPort);

    try
    {
      this.ssdpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
      this.ssdpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);

      this.ssdpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 16384); 

      this.ssdpSocket.Bind(localIpEndpoint);
      this.ssdpSocket.SetSocketOption(
        SocketOptionLevel.IP,
        SocketOptionName.AddMembership,
        new MulticastOption(IPAddress.Parse(SsdpMulticastAddress), localIpAddress));

      this.ssdpSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 2);
      this.ssdpSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, true);

      this.culture = Thread.CurrentThread.CurrentUICulture;
      this.workerThreadListener = new WorkerThread(this.ssdpSocket, this.HandleSsdpMessage);
      this.workerThreadListener.Start();

      Log.InfoFormat("SSDP server bind successful [{0}]", localIpEndpoint);

      return true;
    }
    catch (Exception exception)
    {
      Log.Info(string.Format("SSDP server bind failed [{0}]", localIpEndpoint), exception);
      throw;
    }
  }

  return false;
}

I have found following answer but for me it is not possible to change the port. Is there an alternative solution?

UPnP Multicast

1
Why is it not possible to change the port (or use 0 for any port)? You can't just expect a specific port to be guaranteed to be unused by something else.Jussi Kukkonen
1900 is the standard port for ssdp. So if i want to find all ssdp-deivces on my network I can't change the portKingpin
No, that's a misunderstanding. You (the control point) send your M-SEARCH to 239.255.255.250:1900. The responding devices will send their replies to whatever IP and port you sent from. So you can (and should) let the operating system pick any unused port for you.Jussi Kukkonen
Then why I'm not finding devices when I change the port?Kingpin
@Kingpin you need to change the AddMembership call to hard-code port 1900 rather than using the port from localIpAddresssimonc

1 Answers

0
votes

It's a pure luck this worked for you - rather it worked for reasons different than expected.

You received the NOTIFY messages because you started listening to multicasts as member of the group - UPnP periodically multicast their presence to the neighborhood on 1900, w/o search requests.

On the other hand, when you send M-SEARCH (multicast, presumably), you should stay and listen on the ephemeral port, since unicast responses will be coming there.