问题描述
仅尝试从本地网络中的设备接收UPnP广播。我确实找到了很多类似的问题,并尝试了很多建议,但没有一个主题能成功。我确实用Wireshark看到了UDP数据包,因此实际上是在我的计算机上收到的。有什么建议?
Just trying to receive a UPnP broadcast from a device in my local network. I did find a lot of similar questions and tried a bunch of suggestions, none of theme where successful. I do see the UDP packets with Wireshark, so they are actually received on my computer. Any suggestions?
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;
}
}
推荐答案
感谢尝试错误我通过绑定到多播组时指定本地地址来使其正常工作。我在示例中对地址进行了硬编码,因为它只是一个沙盒应用程序。使用 IPAddress.Any
不起作用。我不知道为什么供将来参考,以及其他可能会寻找类似东西的可怜人:
Thanks to Try and Error I did got it working by specifying my local address while binding to the multicast group. I hardcoded the address in the example since It's is just a sandbox application. Using IPAddress.Any
does not work. I don't know exactly why. For future reference and other poor souls who might looking for similar stuff:
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;
}
}
这篇关于使用UdpClient收听UPnP广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!