C# 修改本地以太网ip地址

因为某项需求,要修改以太网的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 也不会报错

  • 5
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值