Get IPv4 Addresses from Dns.GetHostEntry ()

I have code that works fine on IPv4 machines, but on our build server (IPv6) it fails. In a nutshell:

IPHostEntry ipHostEntry = Dns.GetHostEntry(string.Empty); 

The documentation for GetHostEntry states that passing to string.Empty will get your local host IPv4 address. This is what I want. The problem is that it returns the string ":: 1:" on our IPv6 machine, which I believe is the IPv6 address.

A pinging machine from any other IPv4 device gives a good IPv4 address ... and makes a "ping -4 machine name" from itself, gives the correct IPv4 address .... but regularly pings it from itself, it gives ":: 1:".

How can I get IPv4 for this machine from myself?

+43
c # dns ipv4 ipv6
Jun 29 '09 at 17:38
source share
7 answers

Have you looked at all the addresses in the opposite direction, cancel the InterNetworkV6 family and save only IPv4?

+59
Jun 29 '09 at 17:50
source share

To find all local IPv4 addresses:

 IPAddress[] ipv4Addresses = Array.FindAll( Dns.GetHostEntry(string.Empty).AddressList, a => a.AddressFamily == AddressFamily.InterNetwork); 

or use Array.Find or Array.FindLast if you just want it.

+39
Apr 15 2018-11-11T00:
source share
  public Form1() { InitializeComponent(); string myHost = System.Net.Dns.GetHostName(); string myIP = null; for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++) { if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false) { myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString(); } } } 

Declare myIP and myHost in a public variable and use in any form function.

+6
Oct 15 '10 at 8:43
source share
 IPHostEntry ipHostInfo = Dns.GetHostEntry(serverName); IPAddress ipAddress = ipHostInfo.AddressList .FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork); 
+5
Mar 21 '16 at 21:04
source share
  public static string GetIPAddress(string hostname) { IPHostEntry host; host = Dns.GetHostEntry(hostname); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { //System.Diagnostics.Debug.WriteLine("LocalIPadress: " + ip); return ip.ToString(); } } return string.Empty; } 
+2
Feb 05 '15 at 21:33
source share

To find all valid address lists, this is the code I used

 public static IEnumerable<string> GetAddresses() { var host = Dns.GetHostEntry(Dns.GetHostName()); return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList(); } 
0
Mar 14 '13 at 6:48
source share

IPv6

lblIP.Text = System.Net.Dns.GetHostEntry (System.Net.Dns.GetHostName) .AddressList (0) .ToString ()


IPv4

lblIP.Text = System.Net.Dns.GetHostEntry (System.Net.Dns.GetHostName) .AddressList (1) .ToString ()

0
Feb 19 '15 at 21:12
source share



All Articles