程序中有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
重启电脑再运行程序即可。