我有一个C# .NET客户端,它监听UDP多播消息。我需要在一个网络接口上接收消息。有时我不会看到收到的消息。当我禁用其他接口时,它可以工作。
我试图使用这个站点上类似问题中的代码将套接字选项设置到特定的接口,但是,我不确定这是否只影响发送多播消息而不接收它们?
经过我的研究,我发现路由表导致了这种行为,一种解决方案是更改路由表,但我不喜欢这样做。
在所有接口上加入多播组更好吗?我将如何使用UdpClient来实现这一点。
这是用来设置我的UdpClient的代码
获取接口:
public static IEnumerable<NetworkInterface> GetAvailableMulticastInterfaces()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
List<NetworkInterface> availableInterfaces = new List<NetworkInterface>();
foreach (NetworkInterface adapter in nics)
{
IPInterfaceProperties ip_properties = adapter.GetIPProperties();
if (!adapter.GetIPProperties().MulticastAddresses.Any())
continue; // most of VPN adapters will be skipped
if (!adapter.SupportsMulticast)
continue; // multicast is meaningless for this type of connection
if (OperationalStatus.Up != adapter.OperationalStatus)
continue; // this adapter is off or not connected
IPv4InterfaceProperties p = adapter.GetIPProperties().GetIPv4Properties();
if (null == p)
continue; // IPv4 is not configured on this adapter
availableInterfaces.Add(adapter);
}
return availableInterfaces;
}设置接口:
NetworkInterface networkInterface = Common.Utilities.Network.GetAvailableMulticastInterfaces().Where(nic => nic.Id == attributes.SelectedNetworkInterfaceId).FirstOrDefault();获取接口索引:
networkInterfaceIndex = (int)IPAddress.HostToNetworkOrder(networkInterface.GetIPProperties().GetIPv4Properties().Index);绑定UdpClient:
public void Listen(string multicastGroupAddress, int port, int? networkInterfaceIndex = null)
{
IpAddress = multicastGroupAddress;
Port = port;
_multicastEndPoint = new IPEndPoint(IPAddress.Parse(multicastGroupAddress), port);
Listener = new UdpClient();
Listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
if (networkInterfaceIndex != null)
Listener.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, networkInterfaceIndex.Value);
var localEndpoint = new IPEndPoint(IPAddress.Any, port);
Listener.Client.Bind(localEndpoint);
Listener.JoinMulticastGroup(IPAddress.Parse(multicastGroupAddress));
while (true)
Process();
}发布于 2019-03-14 15:18:53
好的,我回到这里,找到了正确的操作。必须在多个接口上使用
var availableMulticastNics = Utils.GetAvailableMulticastInterfaces();
var listener = new UdpClient();
listener.Client.Bind(new IPEndPoint(IPAddress.Any, endpoint.Port));
foreach (var ni in availableMulticastNics)
{
listener.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastEndPoint.Address, ni.GetIPProperties().GetIPv4Properties().Index));
}
// Ready to read socket而不是listener.JoinMulticastGroup(ni.GetIPProperties().GetIPv4Properties().Index, multicastEndPoint.Address)。否则,我会得到一个SocketException,它告诉我无效的论点,如果有人可以的话,它可以说明一些信息。
https://stackoverflow.com/questions/51860595
复制相似问题