Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gethostbyname in C

I don't know how to write applications in C, but I need a tiny program that does:

lh = gethostbyname("localhost");
output = lh->h_name;

output variable is to be printed.

The above code is used in PHP MongoDB database driver to get the hostname of the computer (hostname is part of an input to generate an unique ID). I'm skeptical that this will return the hostname, so I'd like some proof.

Any code examples would be most helpful.

Happy day.

like image 915
Matic Avatar asked May 19 '10 12:05

Matic


1 Answers

#include <stdio.h>
#include <netdb.h>


int main(int argc, char *argv[])
{
    struct hostent *lh = gethostbyname("localhost");

    if (lh)
        puts(lh->h_name);
    else
        herror("gethostbyname");

    return 0;
}

It is not a very reliable way of determining the hostname, though it may sometimes work. (what it returns depends on how /etc/hosts is set up). If you have a line like:

127.0.0.1    foobar    localhost

...then it will return "foobar". If you have it the other way around though, which is also common, then it will just return "localhost". A more reliable way is to use the gethostname() function:

#include <stdio.h>
#include <unistd.h>
#include <limits.h>

int main(int argc, char *argv[])
{
    char hostname[HOST_NAME_MAX + 1];

    hostname[HOST_NAME_MAX] = 0;
    if (gethostname(hostname, HOST_NAME_MAX) == 0)
        puts(hostname);
    else
        perror("gethostname");

    return 0;
}
like image 62
caf Avatar answered Oct 02 '22 23:10

caf