Belliez
Belliez

Reputation: 5376

.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

Upvotes: 9

Views: 8272

Answers (3)

DavidDraughn
DavidDraughn

Reputation: 1131

dtb's solution will work in many situations. In many cases, however, users may have multiple v4 IPs setup on their system. Sometimes this is because they have some 'virtual' adapters (from applications like VirtualBox or VMWare) or because they have more than one physical network adapter connected to their computer.

It goes without saying that in these situations it's important that the correct IP is used. You may want to consider asking the user which IP is appropriate.

To get a list of usable v4 IPs you can use code similar to:

'Get an array which contains all available IPs: Dim IPList() As IPAddress = Net.Dns.GetHostEntry(Net.Dns.GetHostName.ToString).AddressList

'Copy valid IPs from IPList to FinalIPList
Dim FinalIPList As New ArrayList(IPList.Length)
For Each IP As IPAddress In IPList
    'We want to keep IPs only if they are IPv4 and not a 'LoopBack' device
    '(an InterNetwork AddressFamily indicates a v4 IP)
    If ((Not IPAddress.IsLoopback(IP)) And (IP.AddressFamily = AddressFamily.InterNetwork)) Then
        FinalIPList.Add(IP)
    End If
Next IP

Upvotes: 2

svives
svives

Reputation: 82

For me the solution with the "First" predicate did not work properly, this is the code that works for me:

public static string GetLocalIP() 
        {
            string ipv4Address = String.Empty;

            foreach (IPAddress currrentIPAddress in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (currrentIPAddress.AddressFamily.ToString() == System.Net.Sockets.AddressFamily.InterNetwork.ToString())
                {
                    ipv4Address = currrentIPAddress.ToString();
                    break;
                }
            }

            return ipv4Address;
        }

Upvotes: 0

dtb
dtb

Reputation: 217263

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);

Upvotes: 16

Related Questions