【问题标题】:How can I get computer name and IP address of local computer如何获取本地计算机的计算机名称和 IP 地址
【发布时间】:2011-06-14 07:32:06
【问题描述】:

如何以编程方式获取我的 PC 的计算机名称和 IP 地址?例如,我想在文本框中显示该信息。

【问题讨论】:

标签: c#


【解决方案1】:

看看这个:link

还有这个:link

textBox1.Text = "Computer Name: " + Environment.MachineName

textBox2.Text = "IP Add: " + Dns.GetHostAddresses(Environment.MachineName)[0].ToString();

【讨论】:

  • 获取自己机器的ip地址是可以的,如何获取其他机器的ip地址,而他们登录我们的应用程序?
  • Dns.GetHostAddresses(Environment.MachineName) 只返回当前主机的所有地址的数组。选择该数组的[0] 没有帮助——尤其是当主机可以同时拥有 IPv4 和 IPv6 地址时。这甚至不考虑私有(内部网络)与公共(外部网络)地址。忘记主机是否使用 > 0 个 VPN。选择这个数组的第一个元素是没有用的。
  • 完整编辑我的 cmets - 这些问题已在此处得到解决:stackoverflow.com/questions/1069103/…
【解决方案2】:

查看更多信息:How To Get IP Address Of A Machine

System.Security.Principal.WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;


string strName = p.Identity.Name;


To get the machine name,


System.Environment.MachineName 
or
using System.Net;
strHostName = DNS.GetHostName ();


// Then using host name, get the IP address list..
IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
IPAddress [] addr = ipEntry.AddressList;

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

【讨论】:

    【解决方案3】:

    以简单的方式..

    string IP_Address = Dns.GetHostByName(Environment.MachineName).AddressList[0].toString();
    

    【讨论】:

      【解决方案4】:

      我使用以下网址:https://stackoverflow.com/a/27376368/2510099 IP地址

      public string GetIPAddress()
      {    
         string ipAddress = null;
      
         using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
         {
            socket.Connect("8.8.8.8", 65530); //Google public DNS and port
            IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
            ipAddress = endPoint.Address.ToString();
         }
      
         return ipAddress;
      }
      

      对于机器名

      Environment.MachineName;
      

      【讨论】:

      • 这是一个非常聪明的想法,我认为它适用于很多人。但是,如果您想知道您的系统用于在其他系统之间进行通信的私有 IP 地址,则此技术将无济于事。
      猜你喜欢
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 2019-04-26
      • 2017-10-25
      • 2022-11-02
      • 1970-01-01
      相关资源
      最近更新 更多