2

I've got a small program that detects UPnP devices by sending out a broadcast as shown in the code below. On most computers, this will cause UPnP devices to reply back with information about the device. However, I've seen this fail on 10% of the computers I've tried it on. Does anyone know what could cause this to fail or what I could tweak in my code to make it more reliable?

var _timeout = new TimeSpan(0, 0, 0, 30, 0);

using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {

try {
    s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
    string req = "M-SEARCH * HTTP/1.1\r\n" +
        "HOST: 239.255.255.250:" + port + "\r\n" +
        "ST:upnp:rootdevice\r\n" +
        "MAN:\"ssdp:discover\"\r\n" +
        "MX:3\r\n\r\n";
    byte[] data = Encoding.ASCII.GetBytes(req);
    IPEndPoint ipe = new IPEndPoint(IPAddress.Broadcast, port);
    byte[] buffer = new byte[0x1000];

    DateTime start = DateTime.Now;

    do {
        s.SendTo(data, ipe);
        s.SendTo(data, ipe);
        s.SendTo(data, ipe);

        int length = 0;
        do {
            s.ReceiveTimeout = 30000;
            length = s.Receive(buffer);
        } while (length > 0);
    } while (start.Subtract(DateTime.Now) < _timeout);
} finally {
    if (s != null) {
        s.Close();
    }
}

}

bugfixr
  • 7,997
  • 18
  • 91
  • 144
  • Is it possible that `10% of the computers` have more than one NW interfaces? (physically or virtually because of installed virtual machines) – Eser Sep 05 '15 at 17:30
  • @Eser Probably... I'm guessing there's a way to bind a specific Adapter when using a socket? – bugfixr Sep 06 '15 at 01:38
  • Do the same 10% of devices always fail to respond? Or do you always receive ~90% of the expected replies, but the devices that respod can vary? – simonc Sep 07 '15 at 08:54
  • @simonc Just to be clear, on 10% of the computers this routine runs on, 100% of the UPnP devices don't respond. – bugfixr Sep 07 '15 at 14:11

0 Answers0