1

我正在尝试使用 C# 发现 Belkin Wemo 开关。我通过网络发送 SSDP 以获取交换机的响应。

以下代码段创建一个套接字,发送 SSDP 并等待 2 秒以接收答案。如果没有读取任何内容,它将重新开始。

bool repeat = true;
while (repeat)
{
    UdpClient udpClient = null;
    try
    {
        // Creates the socket.
        udpClient = new UdpClient(10140);
        udpClient.Client.ReceiveTimeout = 2000;
        IPAddress broadcastIpAddress = IPAddress.Parse("239.255.255.250");
        IPEndPoint broadcastIpEndPoint = new IPEndPoint(broadcastIpAddress, 1900);
        udpClient.JoinMulticastGroup(broadcastIpAddress);

        // Sends SSDP.
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.Append("M-SEARCH * HTTP/1.1\r\n");
        stringBuilder.Append("ST: urn:Belkin:service:basicevent:1\r\n");
        stringBuilder.Append("MX: 1\r\n");
        stringBuilder.Append("MAN: \"ssdp:discover\"\r\n");
        stringBuilder.Append("HOST: 239.255.255.250:1900\r\n");
        stringBuilder.Append("\r\n");
        byte[] bytesToSend = Encoding.UTF8.GetBytes(stringBuilder.ToString());
        udpClient.Send(bytesToSend, bytesToSend.Length, broadcastIpEndPoint);

        // Receives response.
        IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        byte[] receivedBytes = udpClient.Receive(ref remoteIpEndPoint);
        string receivedString = Encoding.UTF8.GetString(receivedBytes);
        Console.WriteLine(receivedString);

        repeat = false;
    }
    catch (SocketException) { }
    finally 
    {
        udpClient.Close();
    }
}

大多数情况下,交换机会返回响应。但是,有时它会无限循环而没有得到任何反馈。

我正在使用 Wireshark。在第二种情况下,碰巧没有发送 SSDP。我对此没有任何解释。我的系统是Windows 7,也许它有帮助......

4

0 回答 0