C# - 如何将静态IP地址设置为USB转以太网适配器?

时间:2017-09-13 12:17:21

标签: c# network-interface

我有一个C#应用程序,我需要在其中检测连接到PC的USB转以太网适配器并使用静态IP地址进行设置。适配器可以是任何品牌,我不知道最终用户将拥有哪一个。我所知道的是,只有一个USB转以太网适配器连接到该PC。

这是我当前应该有效的代码:

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;
}

但是,遗憾的是,它没有,当我运行ipconfig时,IP未设置为10.0.0.2,这使我的应用程序的其他部分尝试ping失败。

当我调试代码时,我发现它确实找到了一个ManagementObject,其描述为“USB to Ethernet Adapter”,但其IP不会改变。

我在网上搜索并在MSDN上找到了使用NetworkInterface的代码示例,所以我尝试了这个:

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...
    }
}

是否有100%的方法来检测单个USB适配器并使用静态IP进行设置?

0 个答案:

没有答案