如何获得在C#中的一台机器的IP地址如何获得在C#中的一台机器的IP地址(How to get th

2019-05-12 02:22发布

我如何在C#中的一台机器的IP地址?

Answer 1:

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

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

MSDN链接:

  • Dns.GetHostAddresses
  • IP地址

此外,作为MSalters提到, 127.0.0.1 / ::1是环回地址 ,并且将始终引用到本地计算机。 由于显而易见的原因,但是,它不能被用来从远程计算机连接到本地机器。



Answer 2:

我想要的答案是

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


Answer 3:

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


Answer 4:

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

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

//使用后使用Namespace- System.Net;



文章来源: How to get the IP address of a machine in C#