Get Ipv4 Addresses from Dns.Gethostentry()

Get IPv4 addresses from Dns.GetHostEntry()

Have you looked at all the addresses in the return, discard the ones of family InterNetworkV6 and retain only the IPv4 ones?

Obtain IPV4 Address by default

After searching the documentation based on the comment by @500-InternalServerError I have developed this:

    public IPAddress GetIPV4(IPHostEntry HostInformation)
{
IPAddress[] IP = HostInformation.AddressList;
int index = 0;
foreach (IPAddress Address in IP)
{
if (Address.AddressFamily.Equals(AddressFamily.InterNetwork))
{
break;
}
index++;
}
return HostInformation.AddressList[index];
}

With being invoked by:

IPAddress IP = GetIPV4(Dns.GetHostEntry(Dns.GetHostName()));

Tested and working on 3 machines each with interfaces/addresses spanning from the 1 V4 to 4 Addresses

Trying to get my IPv4 address gets VirtualBox's IPv4

Ok I didn't find a way to get the ip I wanted, but i found a way to get all the available ips with their network adapter name. Here is the code in case anyone wants it:

First Import System.Net.Sockets , System.Net And System.Net.NetworkInformation

The code:

Dim lst As New List(Of String)
For Each adapter As NetworkInterface In NetworkInterface.GetAllNetworkInterfaces
lst.Add(adapter.Description & ": " & adapter.GetIPProperties.UnicastAddresses(1).Address.ToString)
Next

lst is the list with all the network adapters and their ips

Constructing an IPAddress variable using Dns.GetHostEntry

If you just want get an instance of IPAddress for your IP address string representation, than yes, using the DNS for that purpose is absolute overkill.

All sorts of timeouts, latencies, etc. are absolute expected. At least compared to the purely local parsing and disecting of the string representation that happens in IPAddress.Parse(). What that does is, ask the DNS server to resolve the IP address string into a hostname "entry". From that you get the IP address back that you knew all along (albeit as string and not IPAddress).

Now, if you want to be able to "convert" host names into IP addresses in the future, then yes, you need to go via DNS.

But you could always do it in that manner (conceptually):

// First see if it is a valid IP address rep - fast.
IPAddress ip;
if (!IPAddress.TryParse(address, out ip))
{
// See if it is a hostname - slower.
ip = Dns.GetHostEntry(address).AddressList[0];
}

And yes, IPAddress.TryParse() (or Parse()) can handle IPv4 and IPv6 addresses.



Related Topics



Leave a reply



Submit