问题
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;
}
}
回答1:
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;
}
}
来源:https://stackoverflow.com/questions/35793032/listen-to-upnp-broadcast-with-udpclient