指定用于发送多播 IGMP 联接字(C# 套接字)的接口



我想选择使用哪个网络接口来发送加入请求。 这是我尝试过的代码,但我认为这是不正确的:

static int GetNicIndexByIP(String ipAddress)
{
int adapterIndex = -1;
IPAddressInformation[] adapterIPs;
foreach (NetworkInterface adapter in nics)
{
adapterIPs = adapter.GetIPProperties().UnicastAddresses.ToArray();
adapterIndex = (int)IPAddress.HostToNetworkOrder(adapter.GetIPProperties().GetIPv4Properties().Index);
foreach (IPAddressInformation ip in adapterIPs)
{
if (ip.Address.ToString() == ipAddress)
return adapterIndex;
}
}
return -1;
}

string nicAddress = "192.168.1.100";
string multicastAddress = "229.1.0.1";
int nicIndex = GetNicIndexByIP(nicAddress);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// first try: ignored (sent from another interface)
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, nicIndex);
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(multicastAddress)));
// second try: error argument "229.1.0.1" out of range
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(multicastAddress), nicIndex));

如果有人感兴趣,我自己找到了答案:

MulticastOption mcastOption = new MulticastOption(IPAddress.Parse(multicastAddress), IPAddress.Parse(nicAddress));
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOption);

最新更新