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();
}
}
}