我需要使用C#和.NET 3.5从我的程序中获取计算机的实际本地网络IP地址(例如192.168.0.220),在这种情况下,我不能仅使用127.0.0.1。
我应该如何完成这个任务?
我需要使用C#和.NET 3.5从我的程序中获取计算机的实际本地网络IP地址(例如192.168.0.220),在这种情况下,我不能仅使用127.0.0.1。
我应该如何完成这个任务?
此示例代码将枚举所有网络接口并转储已知每个适配器的地址。
using System;
using System.Net;
using System.Net.NetworkInformation;
class Program
{
static void Main(string[] args)
{
foreach ( NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces() )
{
Console.WriteLine("Network Interface: {0}", netif.Name);
IPInterfaceProperties properties = netif.GetIPProperties();
foreach ( IPAddress dns in properties.DnsAddresses )
Console.WriteLine("\tDNS: {0}", dns);
foreach ( IPAddressInformation anycast in properties.AnycastAddresses )
Console.WriteLine("\tAnyCast: {0}", anycast.Address);
foreach ( IPAddressInformation multicast in properties.MulticastAddresses )
Console.WriteLine("\tMultiCast: {0}", multicast.Address);
foreach ( IPAddressInformation unicast in properties.UnicastAddresses )
Console.WriteLine("\tUniCast: {0}", unicast.Address);
}
}
}
您可能最感兴趣的是单播地址(UnicastAddresses)。
使用 DNS 需要您的计算机在本地 DNS 服务器中注册,但如果您连接到内部网络,则不一定需要注册,如果您在家里使用 ISP,则更不可能注册。此外,它还需要进行网络往返,仅为了获取有关您自己计算机的信息。
正确的方法:
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach(NetworkInterface adapter in nics)
{
foreach(var x in adapter.GetIPProperties().UnicastAddresses)
{
if (x.Address.AddressFamily == AddressFamily.InterNetwork && x.IsDnsEligible)
{
Console.WriteLine(" IPAddress ........ : {0:x}", x.Address.ToString());
}
}
}
(更新于2015年7月31日:修复了代码中的一些问题)
或者对于那些只喜欢一行Linq代码的人:
NetworkInterface.GetAllNetworkInterfaces()
.SelectMany(adapter=> adapter.GetIPProperties().UnicastAddresses)
.Where(adr=>adr.Address.AddressFamily == AddressFamily.InterNetwork && adr.IsDnsEligible)
.Select (adr => adr.Address.ToString());
在 John Spano 的 如何使用主机名在 .NET 中获取 IP 地址 中,他说要添加 System.Net
命名空间,并使用以下代码:
//To get the local IP address
string sHostName = Dns.GetHostName ();
IPHostEntry ipE = Dns.GetHostByName (sHostName);
IPAddress [] IpA = ipE.AddressList;
for (int i = 0; i < IpA.Length; i++)
{
Console.WriteLine ("IP Address {0}: {1} ", i, IpA[i].ToString ());
}
一台机器可以有多个IP地址,找到你用于连接互联网的正确IP地址的方法是打开一个到互联网上主机的套接字,然后检查套接字连接以查看在该连接中使用的本地地址。
通过检查套接字连接,您将能够考虑到奇怪的路由表、多个IP地址和奇怪的主机名。上面的主机名技巧可能有效,但我不认为它完全可靠。
Dns.GetHostAddresses(Dns.GetHostName())
.First(a => a.AddressFamily == AddressFamily.InterNetwork).ToString()
GetHostAddresses
通常在查询 DNS 服务器时会阻塞调用线程,并在查询失败时抛出 SocketException
异常。我不知道它在查找自己的主机名时是否跳过网络调用。
NetworkInformation
,C#编译器报错“找不到类型或命名空间”,我已经导入了System.Net.NetworkInformation
,但仍然提示“缺少类型或命名空间”,这是怎么回事? - FosterZforeach ( NetworkInterface ni in nics ) { foreach ( UnicastIPAddressInformation x in ni.GetIPProperties().UnicastAddresses ) { if ( x.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ) { Console.WriteLine( " IPAddress ........ : {0:x}", x.Address.ToString() ); } } }
,它打印出了我的大部分实际 IP 地址和一些不是我的 IP 地址的混合内容。 - user664939