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

4

8

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.

Superhuman answered 14/8, 2008 at 14:37 Comment(0)
P
7

You'll want Win32's GetComputerName:

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

Pawnbroker answered 14/8, 2008 at 14:40 Comment(0)
J
9

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

Jasonjasper answered 14/8, 2008 at 15:22 Comment(1)
Unfortunatly, the link for a) (techbytes.ca) doesn't seem to be available anymore.Quadrilateral
P
7

You'll want Win32's GetComputerName:

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

Pawnbroker answered 14/8, 2008 at 14:40 Comment(0)
H
1

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

}
Hackney answered 16/9, 2008 at 11:21 Comment(0)
M
1

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

Myrticemyrtie answered 8/10, 2015 at 7:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.