您的位置:首页 > 编程语言 > C#

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

2014-07-21 17:57 323 查看
程序中有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

重启电脑再运行程序即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: