How to get the network interface and its right IPv4 address?

I need to know how to get all network interfaces using IPv4 . Or just wireless and Ethernet.

To get information about all network interfaces, I use the following:

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

And to get all hosted IPv4 addresses of a computer:

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

But how to get the network interface and its right ipv4 address?

+45
c # ip-address network-interface
Mar 24 '12 at 20:17
source share
2 answers
 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()); } } } } 

This should get what you want. ip.Address is the IP address you want.

+76
Apr 08 2018-12-12T00:
source share

With some improvement, this code adds any interface to the combination:

 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); } } } 

And when you select one of them, this code returns the IP address of the interface:

 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()); } } } } } 
+1
Dec 14 '13 at 13:32
source share



All Articles