简体   繁体   English

使用WMI / Win32_NetworkAdapterConfiguration轮询C#中的IP地址更改

[英]Polling for IP address change in C# using WMI/Win32_NetworkAdapterConfiguration

I'm making a program that needs to set a static IP to a computer's wired NIC, and the program can't perform the next part (querying an SNMP string from another IP on the same network) until it's positively set and usable, which experience has taught me isn't always instant. 我正在编写一个程序,该程序需要为计算机的有线NIC设置静态IP,并且该程序不能正确设置并可用,因此无法执行下一部分(从同一网络上的另一个IP查询SNMP字符串)。经验告诉我,并不总是即时的。 This program is written in C# on VS2013 as a WinForms application, and the function is below. 该程序是使用VS2013上的C#作为WinForms应用程序编写的,其功能如下。 The actual setting of the IP address works perfectly, the problem is trying to poll for when the change completes. IP地址的实际设置可以正常工作,问题是尝试轮询更改完成的时间。 I can run the program, have it set an IP address (never more than a single IP/Subnet/Gateway), and while it's still polling for the change, pop open a command prompt, run ipconfig, and see that the change has already gone through. 我可以运行该程序,为其设置IP地址(永远不要超过一个IP /子网/网关),并且在仍在轮询更改的同时,弹出打开命令提示符,运行ipconfig,然后查看更改是否已经经历了。 The program will continue to hang until it times out. 该程序将继续挂起,直到超时。 I have tried several different methods of querying and checking the IP addresses, including reassigning NICConfig every time through the loop and checking to see if any IP addresses in either string[] match, nothing works. 我尝试了几种不同的查询和检查IP地址的方法,包括每次通过循环重新分配NICConfig并检查任一string []中的IP地址是否匹配,均无效。 I have not yet piped currentIPs[0] into a file or command line to see what it contains, but I strongly suspect it will contain the previous IP address. 我尚未将currentIPs [0]传送到文件或命令行中以查看其包含的内容,但我强烈怀疑它会包含先前的IP地址。 I also tried setting the IP address in the registry, per this post: Why does applying a static IP address via WMI work just once? 根据这篇文章,我还尝试在注册表中设置IP地址: 为什么通过WMI应用静态IP地址只能工作一次? but all that did for me was give me a second IP address on that interface in ipconfig with the program still hanging. 但是对我来说,所做的就是在ipconfig的该接口上给我第二个IP地址,而程序仍然挂起。

Actually, on further examination, it looks like the behavior is to add the IP address/subnet/gateway to the list (string array), instead of replacing the old info, but the program isn't even getting an updated version of the list with the intended IP on it. 实际上,在进一步检查中,看起来该行为是将IP地址/子网/网关添加到列表(字符串数组),而不是替换旧信息,但是该程序甚至没有获得列表的更新版本。带有预期的IP。 This may not have started until after messing with the registry values using code from the above link, I can't be sure. 可能没有启动,直到使用代码从上面的链接的注册表值搞乱后,我不能肯定。 I also can't seem to remove the extra IPs from my PC's configuration, they don't show up in the windows ipv4 configuration page (but I do get a warning when closing it about multiple gateways), and removing them from the registry seems to do nothing - so any help fixing my computer's NIC configuration would also be appreciated. 我似乎也无法从PC的配置中删除多余的IP,它们不会显示在Windows ipv4配置页中(但在关闭有关多个网关的信息时会收到警告),并且似乎从注册表中删除了它们。什么都不做-因此对修复计算机的NIC配置的任何帮助也将不胜感激。

private bool set_staticIP(string Index, string[] IP, string[] Subnet, string[] Gateway, string[] DNS)
{
    string WMIQuery = String.Format("Win32_NetworkAdapterConfiguration.Index='{0}'", Index);
    ManagementObject NICConfig = new ManagementObject(@"root\CIMV2", WMIQuery, null);
    ManagementBaseObject inParams = null;
    ManagementBaseObject outParams = null;

    string[] OldIP = (string[])NICConfig["IPAddress"];

    try
    {
        /* Set IP/Subnet mask */
        inParams = NICConfig.GetMethodParameters("EnableStatic");
        inParams["IPAddress"] = IP;
        inParams["SubnetMask"] = Subnet;

        outParams = NICConfig.InvokeMethod("EnableStatic", inParams, null);

        if (outParams["ReturnValue"].ToString() != "0")
        {
            MessageBox.Show("Error setting IP, returned " + outParams["ReturnValue"]);
        }

        /* Set Gateway(s) */
        inParams = NICConfig.GetMethodParameters("SetGateways");
        inParams["DefaultIPGateway"] = Gateway;
        inParams["GatewayCostMetric"] = new int[] {1};

        outParams = NICConfig.InvokeMethod("SetGateways", inParams, null);

        if (outParams["ReturnValue"].ToString() != "0")
        {
            MessageBox.Show("Error setting Gateway, returned " + outParams["ReturnValue"]);
        }

        /* Set DNS Servers */
        inParams = NICConfig.GetMethodParameters("SetDNSServerSearchOrder");
        inParams["DNSServerSearchOrder"] = DNS;
        outParams = NICConfig.InvokeMethod("SetDNSServerSearchOrder", inParams, null);

        if (outParams["ReturnValue"].ToString() != "0")
        {
            MessageBox.Show("Error setting DNS, returned " + outParams["ReturnValue"]);
        }

        bool IPMatches = false;
        string[] currentIPs = null;
        int timeout = 2000;
        int i;

        for (i = 0; i < timeout && !IPMatches; i++)
        {
            currentIPs = (string[])NICConfig["IPAddress"];
            if (currentIPs == IP || currentIPs != OldIP)
            {
                IPMatches = true;
                break;
            }
            Task.Delay(100);
        }
        if (i >= timeout)
        {
            MessageBox.Show("Timeout while setting static IP address");
        }

    }
    catch(ManagementException e)
    {
        MessageBox.Show("set_static() threw exception " + e.Message);
    }

    return IPMatches;
}

The machines I've tested this on are a laptop running Windows 7 x64, I get the same behavior with the internal NIC and a USB NIC, and a tablet running Windows 8.1 x64 with the same USB NIC. 我测试过的计算机是运行Windows 7 x64的笔记本电脑,内部NIC和USB NIC的行为相同,而运行Windows 8.1 x64的USB NIC的平板电脑则具有相同的行为。

You can use: 您可以使用:

// Callback für Netzwerk-Änderungen erzeugen
NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(AddressChangedCallback);

// Callback für Netzwerk-Änderungen
void AddressChangedCallback(object sender, EventArgs e)
{
    // IP is changed;
}

You will get the callback whenever a network adress is changed. 每当更改网络地址时,您都会收到回调。 Now you can check if it is the adress you are waiting for. 现在,您可以检查它是否在等待您的地址。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 WMI Win32_NetworkAdapterConfiguration和SetDNSSuffixSearchOrder方法 - WMI Win32_NetworkAdapterConfiguration and SetDNSSuffixSearchOrder method Windows 8中是否提供Win32_Processor和Win32_NetworkAdapterConfiguration WMI方法? - Is the Win32_Processor and Win32_NetworkAdapterConfiguration WMI methods available in Windows 8? win32_NetworkAdapterConfiguration产生的奇怪结果 - Strange results from win32_NetworkAdapterConfiguration 尝试使用 Win32_NetworkAdapterConfiguration 更改 c# 中网络适配器的网络设置(DNS),但我看不出我做错了什么 - Trying to change the network settings(DNS) of a network adapter in c# with Win32_NetworkAdapterConfiguration but I can't see what I'm doing wrong WMI Win32_NetworkAdapterConfiguration “EnableStatic”调用失败并返回结果 0x80041003 - WMI Win32_NetworkAdapterConfiguration “EnableStatic” call fails with return result 0x80041003 Win32_NetworkAdapterConfiguration .NET 4 - 设置静态IP适用于XP但不适用于Windows 7 - Win32_NetworkAdapterConfiguration .NET 4 - Setting Static IP works on XP but not on Windows 7 在 Win32_NetworkAdapterConfiguration 类中使用 ManagementObjectSearcher 进行 LINQ 查询 - LINQ query with ManagementObjectSearcher in Win32_NetworkAdapterConfiguration class 查询Win32_NetworkAdapterConfiguration返回HRESULT:0x80070422 - the query Win32_NetworkAdapterConfiguration return HRESULT: 0x80070422 使用WMI以编程方式更改远程IP地址 - Change remote IP address programmatically using WMI C#使用WMI查询Win32_Fan class和风扇转速返回null? - C# using WMI to query Win32_Fan class and fan speed return null?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM