繁体   English   中英

如何以编程方式获取计算机的本地网络 IP 地址?

[英]How do I get the Local Network IP address of a computer programmatically?

我需要使用 C# 和 .NET 3.5 从我的程序中获取计算机的实际本地网络 IP 地址(例如 192.168.0.220)。 在这种情况下,我不能只使用 127.0.0.1。

我怎样才能做到这一点?

如果您正在寻找命令行实用程序 ipconfig 可以提供的那种信息,您可能应该使用 System.Net.NetworkInformation 命名空间。

此示例代码将枚举所有网络接口并转储每个适配器的已知地址。

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 服务器上注册,如果您在 Intranet 上,则不一定如此,如果您在家中使用 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 的How to get IP address in .NET with a host name 中,它说要添加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 地址,因此确定要用于路由到一般 Internet 的 ip 地址的正确方法是打开一个到 Internet 上主机的套接字,然后检查套接字连接到查看该连接中使用的本地地址是什么。

通过检查套接字连接,您将能够考虑奇怪的路由表、多个 IP 地址和古怪的主机名。 上面使用主机名的技巧可以工作,但我不认为它完全可靠。

如果您知道您的计算机有一个或多个 IPv4 地址,这将提供其中之一:

Dns.GetHostAddresses(Dns.GetHostName())
    .First(a => a.AddressFamily == AddressFamily.InterNetwork).ToString()

GetHostAddresses通常在查询 DNS 服务器时阻塞调用线程,并在查询失败时抛出SocketException 不知道在查找自己的主机名时是否会跳过网络调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM