Skip to main content
 首页 » 编程设计

c#之通过c#获取IP地址(在IPv4值中)

2024年02月20日12jillzhang

<分区>

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

我尝试使用以下代码获取我的 IP 地址,在 XP 中,它返回 IP 地址 V4 格式, 但是当我在我的系统(Windows 7)中执行此操作时,它会以 v6 格式返回 IP 地址。

如何解决这个问题?

代码

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