views:

599

answers:

1

Currently I use the following code to retrieve the IP address of the local workstation...

strIPAddress = System.Net.Dns.GetHostEntry(strComputerName).AddressList(0).ToString()

This is fine for the Windows XP workstations. However, in Vista and Windows 7, this returns the IPv6 address which is not used at all. Is there a method of setting this to work so it always returns the IPv4 address regardless of platform?

I know I can increment the AddressList value to 1 and get the correct IP in Windows 7. The bad part is that this requires going through the motions of identifying the OS and choosing one or the other.

The must be some way of specifying IPv4 only. Perhaps getting a result from DNS on the network rather than the workstation itself?

+2  A: 

You just need to loop through the AddressList looking at the AddressFamily seeing which is set to InterNetwork

Dim IP4 = New List(Of IPAddress)(Dns.GetHostEntry(strComputer).AddressList).Find(Function(f) f.AddressFamily = Sockets.AddressFamily.InterNetwork)

Or the longer way:

    Dim IP4 As IPAddress
    Dim AL = Dns.GetHostEntry(strComputer).AddressList
    For Each A In AL
        If A.AddressFamily = Sockets.AddressFamily.InterNetwork Then
            IP4 = A
            Exit For
        End If
    Next
Chris Haas
Perfect that looks like it'll work. Still some things like that (formatting commands) I still can't wrap my head around.
TheHockeyGeek
You know Chris I was about to lay into you and look really stupid. When I read the question I was thinking of looping through the interfaces, ala System.Net.NetworkInformation.NetworkInterface. Lucky for me I re-read the question ;) All that to say I agree with you. I just went through this a couple of weeks ago when we got our first W7 machine. Many surprises, IPv6 address, why there has to be an ARP entry for broadcast addressesmulticast addressesetc.Anyway, I upvoted you for me thinking evil thoughts and you are correct.
dbasnett