Search code examples
c#.nethttpclientnetwork-interface

Is there a way to specify which NetworkInterface .net will use?


I would like to run a series of tests on a device using its Wifi and LAN connections. I have two network interface cards, one is WiFi, the other is wired. The device has a single IP address that is accessible through both Network Interfaces. Is there a way to guarantee that my machine is using a particular Network Interface so that I can run all tests through the wired connection, and then run all tests through the Wifi connection?

Keep in mind, both connections share the same subnet, so either will successfully connect to the device. I just want to be able to switch back and forth and specify which connection I'm using at any given time.

I'm using HttpClient on .net with C#. Is there a way to force HttpClient to use a particular Network Interface? It seems to automatically choose one based on IP Address, but in this case, there are 2 Network Interfaces that can work. I need to be able to programatically switch back and forth to run my automated tests.

I have noticed something called an 'Interface Metric' that can be changed manually via IP4 Properties Advanced TCP/IP Settings. Will the smaller numbered interface be used every time? Is there a way to change this value programatically?

MORE CLARIFICATION: The reason I didn't directly jump to Disabling the WiFi NIC or the Wired NIC back and forth was when you disable the WiFi NIC, you disconnect the device it was connected to and it doesn't automatically reconnect when you enable it. (even when you say 'connect automatically' it doesn't connect when re-enabled). However, I found a quick solution. Set the Interface Metric on the Wired NIC to be lower than the Interface Metric on the WiFi NIC. Then, just enable and disable the Wired NIC. When disabled, the WiFi NIC will be used by the system. When enabled, the Wired NIC will be used by the system because its Interface Metric is set lower. Now, I just need to figure out how to programatically enable/disable the Wired NIC...


Solution

  • I ended up solving this by setting the Interface Metric on the wired NIC to be lower than the Interface Metric on the Wifi NIC. In this way, I was able to simply disable and enable the Wired NIC which would effectively change which NIC was being used at any time during the test. To Disable the NIC, I use the netsh.exe command with the following code. The 'command' was either 'enable' or 'disable' depending if I was turning it on or off:

            System.Diagnostics.Process p = new System.Diagnostics.Process
            {
                StartInfo =
                {
                    FileName = "netsh.exe",
                    Arguments = $"interface set interface \"{nicName}\" {command}",
                    UseShellExecute = false,
                    RedirectStandardOutput = true
                }
            };
    
            bool started = p.Start();