Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++/Windows how do I get the network name of the computer I'm on?

In a C++ Windows (XP and NT, if it makes a difference) application I'm working on, I need to get the network name associated with the computer the code is executing on, so that I can convert local filenames from C:\filename.ext to \\network_name\C$\filename.ext. How would I do this?

Alternatively, if there's a function that will just do the conversion I described, that would be even better. I looked into WNetGetUniversalName, but that doesn't seem to work with local (C drive) files.

like image 394
Isaac Moses Avatar asked Aug 14 '08 14:08

Isaac Moses


4 Answers

There are more than one alternatives:

a. Use Win32's GetComputerName() as suggested by Stu.
Example: http://www.techbytes.ca/techbyte97.html
OR
b. Use the function gethostname() under Winsock. This function is cross platform and may help if your app is going to be run on other platforms besides Windows.
MSDN Reference: http://msdn.microsoft.com/en-us/library/ms738527(VS.85).aspx
OR
c. Use the function getaddrinfo().
MSDN reference: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx

like image 140
Pascal Avatar answered Oct 22 '22 11:10

Pascal


You'll want Win32's GetComputerName:

http://msdn.microsoft.com/en-us/library/ms724295(VS.85).aspx

like image 7
Stu Avatar answered Oct 22 '22 11:10

Stu


I agree with Pascal on using winsock's gethostname() function. Here you go:

#include <winsock2.h> //of course this is the way to go on windows only

#pragma comment(lib, "Ws2_32.lib")

void GetHostName(std::string& host_name)
{
    WSAData wsa_data;
    int ret_code;

    char buf[MAX_PATH];

    WSAStartup(MAKEWORD(1, 1), &wsa_data);
    ret_code = gethostname(buf, MAX_PATH);

    if (ret_code == SOCKET_ERROR)
        host_name = "unknown";
    else
        host_name = buf;


    WSACleanup();

}
like image 1
jilles de wit Avatar answered Oct 22 '22 13:10

jilles de wit


If you want only the name of the local computer (NetBIOS) use GetComputerName function. It retrives only local computer name that is established at system startup, when the system reads it from the registry.

BOOL WINAPI GetComputerName(
  _Out_   LPTSTR  lpBuffer,
 _Inout_ LPDWORD lpnSize
);

More about GetComputerName

If you want to get DNS host name, DNS domain name, or the fully qualified DNS name call the GetComputerNameEx function.

BOOL WINAPI GetComputerNameEx(
  _In_    COMPUTER_NAME_FORMAT NameType,
  _Out_   LPTSTR               lpBuffer,
  _Inout_ LPDWORD              lpnSize
);

More about GetComputerNameEx

like image 1
Ajay Gupta Avatar answered Oct 22 '22 11:10

Ajay Gupta