Holyoxx
Holyoxx

Reputation: 377

How can I get computer name and IP address of local computer

How can I get the computer name and IP address of my PC programmatically? For example, I want to display that information in a text box.

Upvotes: 12

Views: 39154

Answers (4)

DzSoundNirvana
DzSoundNirvana

Reputation: 81

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;

Upvotes: 0

Jenish Zinzuvadiya
Jenish Zinzuvadiya

Reputation: 1085

In easy way..

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

Upvotes: 0

Rye
Rye

Reputation: 2311

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

Upvotes: 24

Pranay Rana
Pranay Rana

Reputation: 176956

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

Upvotes: 3

Related Questions