如何获得networking接口及其正确的IPv4地址?

我需要知道如何获得所有networking接口与他们的IPv4地址。 或者只是无线和以太网。

要获取所有的networking接口细节我使用这个:

foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { Console.WriteLine(ni.Name); } } 

并获取计算机的所有托pipe的IPv4地址:

 IPAddress [] IPS = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress ip in IPS) { if (ip.AddressFamily == AddressFamily.InterNetwork) { Console.WriteLine("IP address: " + ip); } } 

但如何获得networking接口及其正确的ipv4地址?

 foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { Console.WriteLine(ni.Name); foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { Console.WriteLine(ip.Address.ToString()); } } } } 

这应该得到你想要的。 ip.Address是一个IPAddress,你想要的。

通过一些改进,该代码将任何接口添加到组合中:

 private void LanSetting_Load(object sender, EventArgs e) { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if ((nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) || (nic.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)) //&& (nic.OperationalStatus == OperationalStatus.Up)) { comboBoxLanInternet.Items.Add(nic.Description); } } } 

当select其中一个时,这个代码返回接口的IP地址:

 private void comboBoxLanInternet_SelectedIndexChanged(object sender, EventArgs e) { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation ip in nic.GetIPProperties().UnicastAddresses) { if (nic.Description == comboBoxLanInternet.SelectedItem.ToString()) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { MessageBox.Show(ip.Address.ToString()); } } } } }