使用UdpClient收听UPnP Broadcast

时间:2016-03-04 10:00:27

标签: c# broadcast upnp

只是尝试从本地网络中的设备接收UPnP广播。我确实找到了很多类似的问题并尝试了一堆建议,没有成功的主题。我确实看到了Wireshark的UDP数据包,所以它们实际上是在我的计算机上收到的。有什么建议?

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class UDPListener
{
    private const int listenPort = 1900;

    private static void StartListener()
    {
        bool done = false;

        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, listenPort);

        UdpClient listener = new UdpClient();
        listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);        
        listener.Client.Bind(localEndPoint);
        listener.JoinMulticastGroup(IPAddress.Parse("239.255.255.250"));
        listener.MulticastLoopback = true;

        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 0);

        try
        {
            while (!done)
            {
                Console.WriteLine("Waiting for broadcast");
                var bytes = listener.Receive(ref groupEP);

                Console.WriteLine("Received broadcast from {0} :\n {1}\n",
                   groupEP.ToString(),
                   Encoding.ASCII.GetString(bytes, 0, bytes.Length));

            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            listener.Close();
        }
    }

    public static int Main()
    {
        StartListener();

        return 0;
    }
}

1 个答案:

答案 0 :(得分:3)

感谢Try和Error我确实通过在绑定到多播组时指定我的本地地址来实现它。我在示例中硬编码了地址,因为它只是一个沙箱应用程序。使用IPAddress.Any不起作用。我不知道为什么。为了将来的参考和其他可能寻找类似东西的可怜的灵魂:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class UDPListener
{
    private static void StartListener()
    {
        bool done = false;

        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 1900);

        UdpClient listener = new UdpClient();
        listener.Client.Bind(localEndPoint);
        listener.JoinMulticastGroup(IPAddress.Parse("239.255.255.250"), IPAddress.Parse("10.32.4.129"));

        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 0);

        try
        {
            while (!done)
            {
                Console.WriteLine("Waiting for broadcast");
                var bytes = listener.Receive(ref groupEP);

                Console.WriteLine("Received broadcast from {0} :\n {1}\n",
                   groupEP.ToString(),
                   Encoding.ASCII.GetString(bytes, 0, bytes.Length));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            listener.Close();
        }
    }

    public static int Main()
    {
        StartListener();

        return 0;
    }
}