1

Possible Duplicate:
Get IPv4 addresses from Dns.GetHostEntry()

I try the following code to get my IP address, in XP, it returns the IP address V4 format, but when I do it in my system(windows 7), it return the ip address in v6 format.

How do to solve this?

Code

try
{
      //iphostname = Dns.GetHostName();  // Resolving Host name
      IPHostEntry ipentry = Dns.GetHostEntry(hostLabel.Text);
      IPAddress[] addr = ipentry.AddressList;// Resolving IP Addresses
      for (int i = 0; i < addr.Length; i++)
      {
           try
           {
               ipLabel.Text = Convert.ToString(addr[i]) + "\r\n";
           }
           catch
           {
               ipLabel.Text += "IP Address            | " + "\r\n";
           }
      }
}
catch
{
     //richTextBox1.Text += "Hostname             | " + "\r\n";
}
Community
  • 1
  • 1
houstonCYap
  • 35
  • 1
  • 2
  • 5
  • Try looking here: http://stackoverflow.com/questions/1059526/get-ipv4-addresses-from-dns-gethostentry – Tom Chantler Aug 09 '12 at 09:27
  • "the IP address" doesn't exist - a machine can have multiple IP address. And v6 and v4 addresses aren't two representations of the same thing - a v6 address is separate from a v4 address. – Damien_The_Unbeliever Aug 09 '12 at 09:30

2 Answers2

3
try
           {
               ipLabel.Text += Convert.ToString(addr[i]) + ";";
           }

Since IPv6 is enabled in windows 7 it will return both IPv4 and IPv6 ,and your loop is erasing a few values.

perilbrain
  • 7,961
  • 2
  • 27
  • 35
1

Try this,

 string strHostName = "";
 strHostName = System.Net.Dns.GetHostName();
 IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
 IPAddress[] addr = ipEntry.AddressList;
 ipLabel.Text = addr[addr.Length - 2].ToString();
SuganR
  • 129
  • 1
  • 10