因为某项需求,要修改以太网的ip地址,研究了一段时间,因不太懂网络的知识,只实现了最基本的修改以太网ip的功能。如果有错误,欢迎指出
等价于在这里修改:
实现代码: //设置ip地址 private void SetNetworkAdapter(string ipAddress, string subnetMask, string gateway) { IPAddress ethernetIPAddress = GetEthernetIPAddress(); ManagementBaseObject inPar = null; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if (!(bool)mo["IPEnabled"]) continue; if (((string[])mo["IPAddress"])[0] == ethernetIPAddress.ToString()) { inPar = mo.GetMethodParameters("EnableStatic"); //设置ip地址和子网掩码 inPar["IPAddress"] = new string[] { ipAddress }; inPar["SubnetMask"] = new string[] { subnetMask }; mo.InvokeMethod("EnableStatic", inPar, null); //设置网关地址 if (gateway != null) { inPar = mo.GetMethodParameters("SetGateways"); inPar["DefaultIPGateway"] = new string[] { gateway }; mo.InvokeMethod("SetGateways", inPar, null); } break; } } } //查找以太网ip private IPAddress GetEthernetIPAddress() { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { foreach (var item in adapter.GetIPProperties().UnicastAddresses) { if (item.Address.AddressFamily == AddressFamily.InterNetwork) return item.Address; //item.IPv4Mask获取掩码 } } //adapter.GetIPProperties().GatewayAddresses获取网关 } throw new Exception("Ethernet not connected"); } 注意事项
这里的:
ManagementClass("Win32_NetworkAdapterConfiguration");ManagementObjectCollection moc = mc.GetInstances();
是得到所有的ip(包括wlan、虚拟机),
GetEthernetIPAddress()是获取以太网连接的ip,
加了一个判断:
注意注意注意 程序要以管理员方式运行 否则更改不了ip 也不会报错