Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Read machine IP,Username,Machine name and Domain

1.77/5 (6 votes)
28 Dec 2009CPOL 22.9K  
I plead not guilty, editing this in an attempt to slightly improve it has put my name under it all. I did not write this, all I did was add some comment lines. Luc Pattyn, 28-DEC-2009.This simple code displays how to get machine IP address, Current user name and logged in domain name. Also...
I plead not guilty, editing this in an attempt to slightly improve it has put my name under it all. I did not write this, all I did was add some comment lines. Luc Pattyn, 28-DEC-2009.

This simple code displays how to get machine IP address, Current user name and logged in domain name. Also this code writes all above details into a text file in the local machine.
You need to call following libraries in .NET framework.

C#
using System.IO;//for writing text files
using System.Net;//for read network information like IP,domain
using System.Diagnostics;//for read system info like username, pc name

string pcname, domain, username, ip;
string filepath="C:\\PCdata";  //location of the text file
string logname = "PCInfo.txt";  //name of the text file

pcname = System.Environment.MachineName;   //get machine name
domain = System.Environment.UserDomainName;  //get loggedin domain name
username = System.Environment.UserName;   //get current username


This code will read the IP address of your machine.

protected string Get_IP_Address()
{

   IPHostEntry ipentry = Dns.GetHostEntry(Dns.GetHostName());
   IPAddress[] iparray = ipentry.AddressList;

    // LP: why use a loop when it exits after one iteration anyway?
    for (int i = 0; i < iparray.Length; i++)
    {
          ip = iparray[i].ToString(); // LP: where is ip declared?
          return ip;
     }
          return ip;

  }



And finally, use this code to write your log file (textfile) inside a button click event or any other place.

private void Write_LogOff_File()
{
FileStream fs = new FileStream(@filepath +   logname,FileMode.OpenOrCreate, FileAccess.Write);

StreamWriter m_streamWriter = new StreamWriter(fs);

m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);

m_streamWriter.WriteLine(pcname + " | " + domain + " | " + username + " | " + ip);
m_streamWriter.Flush(); // LP: redundant, as close implies flush.
m_streamWriter.Close(); 
// LP: why not replace it all by a simple File.AppendText()?
}


Remember you can put all these code in any place of your program. Such as button click event, form load or even in form closing.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)