C# 如何以编程方式获取计算机的本地网络 IP 地址?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/151231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the Local Network IP address of a computer programmatically?
提问by Lawrence Johnston
I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case.
我需要使用 C# 和 .NET 3.5 从我的程序中获取计算机的实际本地网络 IP 地址(例如 192.168.0.220)。在这种情况下,我不能只使用 127.0.0.1。
What's the best way to do this?
做到这一点的最佳方法是什么?
采纳答案by PostMan
LinkIt says there, add System.net, and using the following
链接它说在那里,添加 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 ());
}
回答by Jerub
As a machine can have multiple ip addresses, the correct way to figure out your ip address that you're going to be using to route to the general internet is to open a socket to a host on the internet, then inspect the socket connection to see what the local address that is being used in that connection is.
由于一台机器可以有多个 ip 地址,因此确定要用于路由到一般 Internet 的 ip 地址的正确方法是打开一个到 Internet 上主机的套接字,然后检查套接字连接到查看该连接中使用的本地地址是什么。
By inspecting the socket connection, you will be able to take into account weird routing tables, multiple ip addresses and whacky hostnames. The trick with the hostname above can work, but I wouldn't consider it entirely reliable.
通过检查套接字连接,您将能够考虑奇怪的路由表、多个 IP 地址和古怪的主机名。上面使用主机名的技巧可以工作,但我不认为它完全可靠。
回答by GBegen
If you are looking for the sort of information that the command line utility, ipconfig, can provide, you should probably be using the System.Net.NetworkInformation namespace.
如果您正在寻找命令行实用程序 ipconfig 可以提供的那种信息,您可能应该使用 System.Net.NetworkInformation 命名空间。
This sample code will enumerate all of the network interfaces and dump the addresses known for each adapter.
此示例代码将枚举所有网络接口并转储每个适配器的已知地址。
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);
}
}
}
You are probably most interested in the UnicastAddresses.
您可能对 UnicastAddresses 最感兴趣。
回答by James Curran
Using Dns requires that your computer be registered with the local DNS server, which is not necessarily true if you're on a intranet, and even less likely if you're at home with an ISP. It also requires a network roundtrip -- all to find out info about your own computer.
使用 Dns 要求您的计算机在本地 DNS 服务器上注册,如果您在 Intranet 上,则不一定如此,如果您在家中使用 ISP,则不太可能。它还需要网络往返——所有这些都是为了找出有关您自己计算机的信息。
The proper way:
正确的方法:
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());
}
}
}
(UPDATE 31-Jul-2015: Fixed some problems with the code)
(2015 年 7 月 31 日更新:修复了代码的一些问题)
Or for those who like just a line of Linq:
或者对于那些只喜欢一行 Linq 的人:
NetworkInterface.GetAllNetworkInterfaces()
.SelectMany(adapter=> adapter.GetIPProperties().UnicastAddresses)
.Where(adr=>adr.Address.AddressFamily == AddressFamily.InterNetwork && adr.IsDnsEligible)
.Select (adr => adr.Address.ToString());
回答by Edward Brey
If you know there are one or more IPv4 addresses for your computer, this will provide one of them:
如果您知道您的计算机有一个或多个 IPv4 地址,这将提供其中之一:
Dns.GetHostAddresses(Dns.GetHostName())
.First(a => a.AddressFamily == AddressFamily.InterNetwork).ToString()
GetHostAddresses
normally blocks the calling thread while it queries the DNS server, and throws a SocketException
if the query fails. I don't know whether it skips the network call when looking up your own host name.
GetHostAddresses
通常在查询 DNS 服务器时阻塞调用线程,SocketException
如果查询失败则抛出 a 。不知道在查找自己的主机名时是否会跳过网络调用。