views:

1081

answers:

4

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.

+4  A: 

You'll want Win32's GetComputerName:

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

Stu
+7  A: 

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

Pascal
A: 

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

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(bufe, MAX_PATH);

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

    WSACleanup();
}
jilles de wit
A: 

Can you tell me why i got these errors while try to compile program?

Error 7 error LNK1120: 3 unresolved externals Error 6 error LNK2001: unresolved external symbol _gethostname@8 code.obj Error 4 error LNK2001: unresolved external symbol _WSACleanup@0 code.obj Error 5 error LNK2001: unresolved external symbol _WSAStartup@8 code.obj

#define WIN32_LEAN_AND_MEAN
#include <iostream>
#include <windows.h>    
#include <stdio.h>   
#include <tchar.h>   
#include <fstream>
#include <sstream>
#include <string>
#include <time.h>
#include <winsock.h>
using namespace std;

void GetHostName(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 = host_name;

    cout<<"PC name: "<<host_name<<endl;
    system("pause");

    WSACleanup();
}
Profi
This isn't an "answer", but a question. If you want to ask a question, try the "Ask Question" button at the top left of the page.
Charles Bailey
edited for code, but yea, you shouldn't post a qestion as an answer to another question!! specially an old one!
hasen j