C# 使用UdpClient收听UPnP广播
只是尝试从我的本地网络中的设备接收UPnP广播。我确实发现了很多类似的问题,并尝试了一系列的建议,但没有一个是成功的。我确实看到了Wireshark的UDP数据包,所以它们实际上是在我的计算机上接收到的。有什么建议吗C# 使用UdpClient收听UPnP广播,c#,broadcast,upnp,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 = 1
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;
}
}
多亏了Try-and-Error,我在绑定到多播组时指定了我的本地地址,使它能够正常工作。我在示例中硬编码了地址,因为它只是一个沙盒应用程序。使用
IPAddress。任何
都不工作。我不知道确切的原因。供将来参考和其他可能寻找类似材料的可怜人:
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;
}
}
看看这个,也许会对你有帮助:(我知道这个很旧,但它仍然相关)非常感谢!似乎是
localEndPoint
中的端口1900为我做了这件事。localEndPoint
最好使用0
作为端口,而不是1900
,因为在某些情况下,如果1900
已经很忙,则无法重用它