Search code examples
c++gethostbyname

passing char by pointer and getting a different result


I am using gethostname to get the name of the computer I am working on. In my main function I call it and get UBU24-PS-23 the correct name of my computer. Then I call a function and that uses the gethostname and I get a different string. In my main function gethostname returns 0 so it works, in my function it returns -1 so it fails. Any ideas why? Here is my code

 #include <iostream>
 #include <sys/unistd.h>
 using namespace std;


int funToGetHostName(char * name, size_t len);
int main() {

char hostname[128];
char hostnameFunction[128];

int g = gethostname(hostname, sizeof hostname);
int r = funToGetHostName(hostnameFunction, sizeof hostnameFunction);
cout<<"My hostname: %s\n"<< hostname<< " "<< g<<endl;
cout<<"My hostnameFunction: %s\n"<< hostnameFunction<< " "<< r;

return 0;
}

int funToGetHostName(char * name, size_t len){
    return gethostname(name, sizeof len);
}

Solution

  • int funToGetHostName(char * name, size_t len){
        return gethostname(name, sizeof len);
    }
    

    sizeof len is likely to be much smaller than you expect.

    Instead, you want:

        return gethostname(name, len);
    

    since you already passed in the buffer length while calling your function.