【发布时间】:2011-06-14 07:32:06
【问题描述】:
如何以编程方式获取我的 PC 的计算机名称和 IP 地址?例如,我想在文本框中显示该信息。
【问题讨论】:
标签: c#
如何以编程方式获取我的 PC 的计算机名称和 IP 地址?例如,我想在文本框中显示该信息。
【问题讨论】:
标签: c#
【讨论】:
Dns.GetHostAddresses(Environment.MachineName) 只返回当前主机的所有地址的数组。选择该数组的[0] 没有帮助——尤其是当主机可以同时拥有 IPv4 和 IPv6 地址时。这甚至不考虑私有(内部网络)与公共(外部网络)地址。忘记主机是否使用 > 0 个 VPN。选择这个数组的第一个元素是没有用的。
查看更多信息: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 ());
}
【讨论】:
以简单的方式..
string IP_Address = Dns.GetHostByName(Environment.MachineName).AddressList[0].toString();
【讨论】:
我使用以下网址: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;
【讨论】: