C# - How to set static IP address to USB to Ethernet adapter?

1.7k views Asked by At

I have a C# application in which I need to detect a USB to Ethernet adapter connected to a PC and set it with a static IP address. The adapter can be of any brand, I don't know which one the end user will have. All I do know is that it will be only one USB to Ethernet adapter connected to that PC.

Here is my current code which should have worked:

public static bool SetStaticIPAddress(out string exception)
{
    const string USBtoEthernetAdapter = "USB to Ethernet Adapter";

    var adapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
    var networkCollection = adapterConfig.GetInstances();
    foreach (ManagementObject adapter in networkCollection)
    {
        string description = adapter["Description"] as string;

        if (description.StartsWith(USBtoEthernetAdapter, StringComparison.InvariantCultureIgnoreCase))
        {
            try
            {
                var newAddress = adapter.GetMethodParameters("EnableStatic");
                newAddress["IPAddress"] = new string[] { "10.0.0.2"};
                newAddress["SubnetMask"] = new string[] { "255.255.255.0"};

                adapter.InvokeMethod("EnableStatic", newAddress, null);
                exception = null;
                return true;
            }
            catch (Exception ex)
            {
                exception = $"Unable to Set IP: {ex.Message}";
                return false;
            }
        }
    }
    exception = $"Could not find any \"{USBtoEthernetAdapter}\" device connected";
    return false;
}

But, unfortunately , it doesn't and when I run ipconfig the IP is not set to 10.0.0.2 and this makes other parts of my app that tries to ping it to fail...

When I debug the code I see that it does find a ManagementObject with the description "USB to Ethernet Adapter" but its IP doesn't change.

I searched the web and found on MSDN this code sample that uses NetworkInterface so I tried this:

NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
    IPInterfaceProperties properties = adapter.GetIPProperties();
    // This is the name of the USB adapter but I can't relay on this name
    // since I don't know which device the user will use except for the fact
    // that is will be a USB to Ethernet Adapter...
    if (adapter.Description == "Realtek USB FE Family Controller")
    {
        // No way to set the device IP here...
    }
}

Is there a 100% way to detect that single USB adapter and set it with the static IP?

0

There are 0 answers