-1

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));
2
  • So, you would like to detect the network interface with multicast address? Commented Jun 1, 2020 at 7:33
  • I would like to send the join packet from a specific interface Commented Jun 1, 2020 at 7:47

1 Answer 1

0

if anyone is interested, I found the answer myself:

MulticastOption mcastOption = new MulticastOption(IPAddress.Parse(multicastAddress), IPAddress.Parse(nicAddress));
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOption);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.