IPHostEntry GetHostEntry IPv6 or IPv4 ?

I've been using the following code to return an IP (v4) from a host name. However, this doesn't work on Vista IPv6 address returns.

Q. How can I change this code to detect the OS and find the IP per Host name accordingly?

        private IPAddress GetIP()
        {
            IPAddress thisIp = null;

            string strHostName = Dns.GetHostName();
            IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);// Find host name

            foreach (IPAddress ipAddress in iphostentry.AddressList)// Grab the first IP addresses
            {
                thisIp = ipAddress;
            }
            return thisIp;
        }

pointemanAsked:
Who is Participating?
 
Todd GerbertIT ConsultantCommented:
In the foreach loop, you can check the AddressFamily property of each address and return the first IPv4 one found. On my system, that's actually the third one in the list.
static private IPAddress GetIP()
        {
            IPAddress thisIp = null;

            string strHostName = Dns.GetHostName();
            IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);// Find host name

            foreach (IPAddress ipAddress in iphostentry.AddressList)// Grab the first IP addresses
            {
                if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    thisIp = ipAddress;
            }
            return thisIp;
        }

Open in new window

0
 
pointemanAuthor Commented:
Your code works well.
Q. Will every Vista, Seven, etc O/S return an IPv4 upon  request?
0
 
Todd GerbertIT ConsultantCommented:
There is no guarantee that every system will have an IPv4 address.  I should also point out that it is possible for a host to have more than one IPv4 address; the function above simply returns the *first* IPv4 address in the list, or null if there are no IPv4 addresses.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.