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

时间:2022-07-25 02:56:56

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

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

4 个解决方案

#1


32  

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:

Alternatively, as MSalters mentioned, 127.0.0.1 / ::1 is the loopback address and 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是环回地址,并且将始终引用本地计算机。但是,由于显而易见的原因,它不能用于从远程计算机连接到本地计算机。

#2


8  

My desired answer was

我想要的答案是

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

#3


1  

 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 ());
 }

#4


0  

 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;

#1


32  

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:

Alternatively, as MSalters mentioned, 127.0.0.1 / ::1 is the loopback address and 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是环回地址,并且将始终引用本地计算机。但是,由于显而易见的原因,它不能用于从远程计算机连接到本地计算机。

#2


8  

My desired answer was

我想要的答案是

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

#3


1  

 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 ());
 }

#4


0  

 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;