如何在C#中获取机器的IP地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2019431/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:43:52  来源:igfitidea点击:

How to get the IP address of a machine in C#

c#.netip-address

提问by Azhar

How do I get the IP address of a machine in C#?

如何在 C# 中获取机器的 IP 地址?

采纳答案by Richard Szalay

IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

Your machine doesn't have a single IP address, and some of the returned addresses can be IPv6.

你的机器没有一个单一的 IP 地址,一些返回的地址可以是 IPv6。

MSDN links:

MSDN 链接:

Alternatively, as MSaltersmentioned, 127.0.0.1/ ::1is the loopback addressand will always refer to the local machine. For obvious reasons, however, it cannot be used to connect to the local machine from a remote machine.

或者,正如MSalters 所提到的,127.0.0.1/::1环回地址,并且总是指本地机器。然而,由于显而易见的原因,它不能用于从远程机器连接到本地机器。

回答by Gopi

 IPHostEntry ip = DNS.GetHostByName (strHostName);
 IPAddress [] IPaddr = ip.AddressList;

 for (int i = 0; i < IPaddr.Length; i++)
 {
  Console.WriteLine ("IP Address {0}: {1} ", i, IPaddr[i].ToString ());
 }

回答by Azhar

My desired answer was

我想要的答案是

string ipAddress = "";
if (Dns.GetHostAddresses(Dns.GetHostName()).Length > 0)
{
     ipAddress = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
}

回答by Ranjeet

 string hostName = Dns.GetHostName(); // Retrive the Name of HOST

           // Get the IP
            string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();

//use Following Namespace- using System.Net;

//使用以下命名空间-使用System.Net;