Getting IP Address

In C #:

IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName()); for (int i = 0; i < IPHost.AddressList.Length; i++) { textBox1.AppendText("My IP address is: " + IPHost.AddressList[i].ToString() + "\r\n"); } 

In this code, the IPHostEntry variable contains all the IP addresses of the computer. Now, as far as I know, Windows Vista returns several IP addresses in hexadecimal, some in decimal notation, etc.

The problem is that the desired decimal notation changes its location in the IPHostEntry variable: it originally occurred in the last place and therefore could be accessed with the code:

 string ipText = IPHost.AddressList[IPHost.AddressList.Length - 1].ToString(); 

However, after changing the IP address of the computer, it now appears in the 2nd last place and therefore should be accessible using the code:

 string ipText = IPHost.AddressList[IPHost.AddressList.Length - 2].ToString(); 

Is there any code that retrieves the IP addresses in decimal notation regardless of its location in the IPHostEntry variable ??

+4
source share
3 answers

Assuming you only need an IPv4 address, I am currently using this code (slightly modified for publication), which is strong enough for my use. Just call ToString on the result to get the address:

 // return the first IPv4, non-dynamic/link-local, non-loopback address public static IPAddress GetIPAddress() { IPAddress[] hostAddresses = Dns.GetHostAddresses(""); foreach (IPAddress hostAddress in hostAddresses) { if (hostAddress.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(hostAddress) && // ignore loopback addresses !hostAddress.ToString().StartsWith("169.254.")) // ignore link-local addresses return hostAddress; } return null; // or IPAddress.None if you prefer } 

Part 169.254. * may seem hacked, but documented in IETF RFC 3927 .

+9
source

I believe that you are asking if you can distinguish between the IPv4 and IPv6 addresses returned from your DNS query. The answer is yes. Check the AddressFamily property on IPAddress and make sure it returns InterNetwork .

+1
source

Your hexadecimal addresses are IPv6, 4 decimal numbers are ipv4.

+1
source

Source: https://habr.com/ru/post/1286594/


All Articles