C# 通过 ManagementClass 获取本机IP 地址 报错

     程序中有IP地址限制的功能,需要获取本机的IP 地址信息。通过 ManagementClass 类来获取本机的IP 地址信息。代码如下:

 public static System.Collections.Generic.List<IPIdentity> GetLocalIPAdressList()
        {
            string ip = string.Empty;
            string subNet = string.Empty;
            System.Collections.Generic.List<IPIdentity> list = new System.Collections.Generic.List<IPIdentity>();
            ManagementObjectCollection instances = new ManagementClass("Win32_NetworkAdapterConfiguration").GetInstances();
            foreach (ManagementObject obj2 in instances)
            {
                if (System.Convert.ToBoolean(obj2.get_Item("ipEnabled")))
                {
                    ip = (obj2.get_Item("IPAddress") as string[])[0];
                    subNet = (obj2.get_Item("IPSubnet") as string[])[0];
                    if (!(string.IsNullOrEmpty(ip) || string.IsNullOrEmpty(subNet)))
                    {
                        IPIdentity identity = new IPIdentity(ip, subNet);
                        list.Add(identity);
                    }
                }
            }
            return list;
        }

但是在某些电脑上报错,显示的错误也为空。电脑上的【网络连接】也找不到。


原因:电脑上的 Network Connections 服务未启动。


解决方法:我的电脑——右键——管理——服务和应用程序——服务——启动 Network Connections

              重启电脑再运行程序即可。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值