[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2774
  • Last Modified:

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

0
pointeman
Asked:
pointeman
  • 2
2 Solutions
 
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now