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

In C ++ Windows (XP and NT, if that matters) the application I'm working on, I need to get the network name associated with the computer on which the code is running so that I can convert local file names from C: \ filename. ext - \\ network_name \ C $ \ filename.ext. How can I do it?

Alternatively, if there is a function that will just perform the conversion that I described, it will be even better. I looked at WNetGetUniversalName, but this does not seem to work with local (C files).

+7
c ++ windows-xp networking windows-nt
source share
4 answers
+7
source share

There are several alternatives:

but. Use Win32 GetComputerName () as suggested by Stu.
Example: http://www.techbytes.ca/techbyte97.html
OR
b. Use the gethostname () function under Winsock. This feature is cross-platform and can help if your application runs on platforms other than Windows.
MSDN link: http://msdn.microsoft.com/en-us/library/ms738527(VS.85).aspx
OR
from. Use the getaddrinfo () function.
MSDN link: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx

+9
source share

I agree with Pascal in using the winsock gethostname () function. Here you are:

#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(); } 
+1
source share

If you want only the local computer name (NetBIOS) to use the GetComputerName . It retrieves only the name of the local computer, which is installed when the system starts, when the system reads it from the registry.

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

Learn more about GetComputerName

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

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

Learn more about GetComputerNameEx

0
source share

All Articles