ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-30 15:09:18  阅读:370  来源: 互联网

标签:unmanaged dllimport c net


我正在使用以下代码将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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有