Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net IPAddress IPv4

I have the following code:

Dim ipAdd As IPAddress = Dns.GetHostEntry(strHostname).AddressList(0)
Dim strIP As String = ipAdd.ToString()

When I convert to String instead of an IPv4 address like 192.168.1.0 or similar I get the IPv6 version: fd80::5dbe:5d89:e51b:d313 address.

Is there a way I can return the IPv4 address from IPAddress type?

Thanks

like image 672
Belliez Avatar asked Jan 12 '10 10:01

Belliez


People also ask

What is System Net IP address?

The IPAddress class contains the address of a computer on an IP network. Example. The following example creates an IPAddress instance and then uses that instance to perform a DNS query for host information: IPAddress myIP = IPAddress.

Which is IP address for IPv4?

The IPv4 address is a 32-bit number that uniquely identifies a network interface on a machine. An IPv4 address is typically written in decimal digits, formatted as four 8-bit fields that are separated by periods. Each 8-bit field represents a byte of the IPv4 address.

How do I know if my IP is v4 or v6 Python?

In your Python program you might want to validate an IP address. This can be a requirement if you write OS level programs and not only. To validate an IP address using Python you can use the ip_address() function of the ipaddress module. This works both for IPv4 and IPv6 addresses.


1 Answers

Instead of unconditionally taking the first element of the AddressList, you could take the first IPv4 address:

var address = Dns.GetHostEntry(strHostname)
                 .AddressList
                 .First(ip => ip.AddressFamily == AddressFamily.InterNetwork);
like image 169
dtb Avatar answered Nov 02 '22 20:11

dtb