UPnP设备无法响应广播

时间:2015-09-05 15:36:30

标签: c# upnp

我有一个小程序,通过发送广播来检测UPnP设备,如下面的代码所示。在大多数计算机上,这将导致UPnP设备回复有关设备的信息。但是,我已经看到这种情况在10%我尝试过的计算机上失败了。有谁知道可能导致这种情况失败的原因或者我可以在我的代码中调整哪些内容以使其更可靠?

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

}

0 个答案:

没有答案
相关问题