C#根据网络适配器获取本机ip
电脑版发表于:2019/11/18 13:47
直接调用下面方法即可:
private IList<string> GetHostIpForFas() { try { IList<string> strIp = new List<string>(); //NetworkInterface:提供网络接口的配置和统计信息。 NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection allAddress = adapterProperties.UnicastAddresses; //这里是根据网络适配器名称找到对应的网络 if (allAddress.Count > 0 && adapter.Name == "WLAN 2") { foreach (UnicastIPAddressInformation addr in allAddress) { if (addr.Address.AddressFamily == AddressFamily.InterNetwork) { strIp.Add(addr.Address.ToString()); } } } } return strIp; } catch (Exception ex) { return null; } }
实际上获取的就是电脑上的网络属性信息,见下图: