我正在运行一个服务器,我想显示我自己的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;
然而,我通常不信任作者,我不理解这段代码。有更好的方法吗?
使用LINQ获取所有IP地址为字符串:
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
...
string[] allIpAddresses = NetworkInterface.GetAllNetworkInterfaces()
.SelectMany(c=>c.GetIPProperties().UnicastAddresses
.Where(d=>d.Address.AddressFamily == AddressFamily.InterNetwork)
.Select(d=>d.Address.ToString())
).ToArray();
为了过滤掉私人信息…
首先,定义一个扩展方法IsPrivate():
public static class IPAddressExtensions
{
// Collection of private CIDRs (IpAddress/Mask)
private static Tuple<int, int>[] _privateCidrs = new []{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"}
.Select(c=>Tuple.Create(BitConverter.ToInt32(IPAddress
.Parse(c.Split('/')[0]).GetAddressBytes(), 0)
, IPAddress.HostToNetworkOrder(-1 << (32-int.Parse(c.Split('/')[1])))))
.ToArray();
public static bool IsPrivate(this IPAddress ipAddress)
{
int ip = BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0);
return _privateCidrs.Any(cidr=>(ip & cidr.Item2)==(cidr.Item1 & cidr.Item2));
}
}
... 然后用它来过滤私人ip:
string[] publicIpAddresses = NetworkInterface.GetAllNetworkInterfaces()
.SelectMany(c=>c.GetIPProperties().UnicastAddresses
.Where(d=>d.Address.AddressFamily == AddressFamily.InterNetwork
&& !d.Address.IsPrivate() // Filter out private ones
)
.Select(d=>d.Address.ToString())
).ToArray();