Get the local computer name using C++

Knowing the name of the computer your program is currently running on is sometimes something which can be very handy. Doing a computer name lookup is a simple Windows API call. If you haven't used Windows API before, make sure to check out MSDN which contains a lot of good documentation on the API calls.

To simply get the NetBIOS computer name, you just have to use the GetComputerName API call. If you are looking for more information, such as the fully qualified DNS name, use the GetComputerNameEx function.

Here is a simple function which demonstrates how to get the computer name. NOTE: This code works with the Borland compiler and might have to be modified slightly for use with other compilers.

#include <windows.h>
#include <string>
#include <iostream.h>

string GetLocalComputerName() { 
  TCHAR chrComputerName[MAX_COMPUTERNAME_LENGTH + 1]; 
  string strRetVal; 
  DWORD dwBufferSize = MAX_COMPUTERNAME_LENGTH + 1; 
  
  if(GetComputerName(chrComputerName,&dwBufferSize)) { 
    // We got the name, set the return value. 
    strRetVal = chrComputerName; 
  } else { 
    // Failed to get the name, call GetLastError here to get 
    // the error code. 
    strRetVal = ""; 
  } 

  return(strRetVal); 
}

And that's it. The function returns the computer name in a string at which point you can do whatever you need to do with it.


Author: DPAK
Created: Nov 30 2005
Categories: C++
TechByte #97

Warning: By visiting this site and/or by using any information contained herein, you agree to the Techbytes.ca terms of use.


Comment posted by 'Anonymous' on Jul 6 2007 @ 13:03:44
Really good... Helped me on time.
Comment posted by 'Anonymous' on Nov 8 2007 @ 11:16:16
Hey thanx..just wat i was looking for
Comment posted by 'Ili Isabel' on May 5 2008 @ 22:11:41
Thaks about your aport!!
I had implement in my application and work so good!!!

:D

Add a comment about this TechByte

If you wish to add a comment regarding this TechByte, please use the form below. Please note that by submitting comments using this form you are allowing all of the information submitted to be visible on this website. Any comments submitted using this form will only be shown on the website if they are approved by the administrators of this site. IF APPROVED, COMMENTS MAY TAKE SEVERAL DAYS TO BE POSTED.

Posted By: (Optional)

Comments:


Other TechBytes: