65.9K
CodeProject is changing. Read more.
Home

Read machine IP,Username,Machine name and Domain

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.77/5 (6 votes)

Dec 14, 2009

CPOL
viewsIcon

23039

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.
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.