Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine the local host’s IPv4 addresses?

How do I get only Internet Protocol version 4 addresses from Dns.GetHostAddresses()? I have the code below, and it gives me IPv4 and IPv6 addresses. I have to make it work with boxes that have multiple IPv4 addresses.

IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName()); private void get_IPs()     {         foreach (IPAddress a in localIPs)         {            server_ip = server_ip + a.ToString() + "/";         }     } 
like image 865
John Ryann Avatar asked Jul 12 '11 17:07

John Ryann


People also ask

How do I find the IPv4 address?

On an Android/tabletGo to your Wifi network settings, then select the network you're connected to. You'll find your IP address along with the other network information.

What is the IPv4 address of the host?

IPv4 addresses are 32-bit numbers that are typically displayed in dotted decimal notation. A 32-bit address contains two primary parts: the network prefix and the host number. All hosts within a single network share the same network address. Each host also has an address that uniquely identifies it.


2 Answers

From my blog:

/// <summary>  /// This utility function displays all the IP (v4, not v6) addresses of the local computer.  /// </summary>  public static void DisplayIPAddresses()  {      StringBuilder sb = new StringBuilder();       // Get a list of all network interfaces (usually one per network card, dialup, and VPN connection)      NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();       foreach (NetworkInterface network in networkInterfaces)      {          // Read the IP configuration for each network          IPInterfaceProperties properties = network.GetIPProperties();           // Each network interface may have multiple IP addresses          foreach (IPAddressInformation address in properties.UnicastAddresses)          {              // We're only interested in IPv4 addresses for now              if (address.Address.AddressFamily != AddressFamily.InterNetwork)                  continue;               // Ignore loopback addresses (e.g., 127.0.0.1)              if (IPAddress.IsLoopback(address.Address))                  continue;               sb.AppendLine(address.Address.ToString() + " (" + network.Name + ")");          }      }       MessageBox.Show(sb.ToString());  } 

In particular, I do not recommend Dns.GetHostAddresses(Dns.GetHostName());, regardless of how popular that line is on various articles and blogs.

like image 127
Stephen Cleary Avatar answered Sep 27 '22 23:09

Stephen Cleary


add something like this to your code

  if( IPAddress.Parse(a).AddressFamily == AddressFamily.InterNetwork )   // IPv4 address 
like image 43
Joost Evertse Avatar answered Sep 28 '22 00:09

Joost Evertse