我正在使用此代码将 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 绑定到网卡?