How can I get the computer name and IP address of 开发者_StackOverflowmy PC programmatically? For example, I want to display that information in a text box.
Have a look at this: link
and this: link
textBox1.Text = "Computer Name: " + Environment.MachineName
textBox2.Text = "IP Add: " + Dns.GetHostAddresses(Environment.MachineName)[0].ToString();
Check more about this : 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 ());
}
In easy way..
string IP_Address = Dns.GetHostByName(Environment.MachineName).AddressList[0].toString();
I use the following found at: https://stackoverflow.com/a/27376368/2510099 for the IP address
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;
}
and for the machine name
Environment.MachineName;
精彩评论