编程语言
首页 > 编程语言> > c#-在.net中使用iphlpapi.dll在x64计算机上添加新的IP地址

c#-在.net中使用iphlpapi.dll在x64计算机上添加新的IP地址

作者:互联网

我正在使用以下代码将IP地址添加到网卡:

[DllImport("iphlpapi.dll", SetLastError = true)]
        private static extern UInt32 AddIPAddress(UInt32 address, UInt32 ipMask, int ifIndex, out IntPtr nteContext,
                                                  out IntPtr nteInstance);

public static UInt32 AddIpAddressToInterface(string ipAddress, string subnetMask, int ifIndex)
        {
            var ipAdd = System.Net.IPAddress.Parse(ipAddress);
            var subNet = System.Net.IPAddress.Parse(subnetMask);
            unsafe
            {
                var nteContext = 0;
                var nteInstance = 0;
                IntPtr ptrNteContext;
                var ptrNteInstance = new IntPtr(nteInstance);
                return AddIPAddress((uint)BitConverter.ToInt32(ipAdd.GetAddressBytes(), 0), (uint)BitConverter.ToInt32(subNet.GetAddressBytes(), 0), ifIndex, out ptrNteContext,
                                    out ptrNteInstance);
            }
        }

它似乎正在运行,但是我注意到如果重新启动计算机,则IP将被删除.另外,如果我从命令行执行ipconfig,则可以看到它们,但是在“高级TCP / IP设置”对话框中看不到它们.那么,是否真的添加了IPS或我需要做其他事情以确保IP已绑定到NIC卡?

解决方法:

实际上添加了IP,但AddIPAddress是非持久性的:

The IPv4 address added by the AddIPAddress function is not persistent. The IPv4 address exists only as long as the adapter object exists. Restarting the computer destroys the IPv4 address, as does manually resetting the network interface card (NIC). Also, certain PnP events may destroy the address.

To create an IPv4 address that persists, the EnableStatic method of the Win32_NetworkAdapterConfiguration Class in the Windows Management Instrumentation (WMI) controls may be used. The netsh commands can also be used to create a persistent IPv4 address.

来源:http://msdn.microsoft.com/en-us/library/windows/desktop/aa365801%28v=vs.85%29.aspx

您可以使用WMI.NET(System.Management命名空间)执行EnableStatic方法,如下所示:

var q = new ObjectQuery("select * from Win32_NetworkAdapterConfiguration where InterfaceIndex=25");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(q);

foreach (ManagementObject nic in searcher.Get()) 
{
    ManagementBaseObject newIP = nic.GetMethodParameters("EnableStatic");
    newIP["IPAddress"] = new string[]{"192.168.0.1"};
    newIP["SubnetMask"] = new string[]{"255.255.255.0"};
    nic.InvokeMethod("EnableStatic", newIP, null); 
}

标签:unmanaged,dllimport,c,net
来源: https://codeday.me/bug/20191030/1968625.html