我遇到这个问题,我写了一个小应用程序来显示计算机的主机名和IP地址。
Hostname horks没有问题,我坐的问题是......
在某些Windows 7/8计算机上显示IPv6 Frown | :(
如何强制每次只返回IPv4?
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace IPChecker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "Host Computer: " + Dns.GetHostName();
foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName()))
{
label2.Text = "IP Address: " + address;
}
}
}
}
答案 0 :(得分:1)
试试这个..
声明一个字符串..
public static string Ipv4()
{
string ipv4Address = String.Empty;
foreach (IPAddress currentIPAddress in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (currentIPAddress.AddressFamily.ToString() == System.Net.Sockets.AddressFamily.InterNetwork.ToString())
{
ipv4Address = currentIPAddress.ToString();
break;
}
}
return ipv4Address;
}
答案 1 :(得分:1)
您是否尝试使用空主机名?
关注MSDN(http://msdn.microsoft.com/en-us/library/system.net.dns.gethostaddresses(v=vs.110).aspx):
当空字符串作为主机名传递时,此方法返回除Windows Server 2003以外的所有操作系统的本地主机的IPv4地址;对于Windows Server 2003,将返回本地主机的IPv4和IPv6地址。