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 a number of IP addresses some in hexadecimal, some in decimal notation and so on.
The problem is that the decimal notation which is desired changes its location in the IPHostEntry
variable: It initially was occuring in the last location and so 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 location and so needs to be accessed using the code:
string ipText = IPHost.AddressList[IPHost.AddressList.Length - 2].ToString();
Is there any code that retrieves the IP addresses in decimal notation irrespective of its location in the IPHostEntry
variable??
Assuming you only want the IPv4 address, I'm currently using this code (modified a bit for posting) which is robust enough for my use. Just invoke 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
}
The 169.254.* part might seem like a hack, but is documented in IETF RFC 3927.
I believe what you are asking is can you differentiate between the IPv4 and IPv6 address returned from your DNS query. The answer is yes. Check the AddressFamily property on the IPAddress and make sure it returns InterNetwork.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With