I would like to choose which network interface to use to send a join request. This is the code I tried but I don't think it's right:
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));