Question

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.

Was it helpful?

Solution

OTHER TIPS

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

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();

}

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top