我正在运行一个服务器,我想显示我自己的IP地址。
获取计算机自身(如果可能的话,外部)IP地址的语法是什么?
有人编写了以下代码。
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
return localIP;
然而,我通常不信任作者,我不理解这段代码。有更好的方法吗?
为了找到IP地址列表,我已经使用了这个解决方案
public static IEnumerable<string> GetAddresses()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}
但我个人喜欢下面的解决方案,以获得本地有效的IP地址
public static IPAddress GetIPAddress(string hostName)
{
Ping ping = new Ping();
var replay = ping.Send(hostName);
if (replay.Status == IPStatus.Success)
{
return replay.Address;
}
return null;
}
public static void Main()
{
Console.WriteLine("Local IP Address: " + GetIPAddress(Dns.GetHostName()));
Console.WriteLine("Google IP:" + GetIPAddress("google.com");
Console.ReadLine();
}