Friday, July 10, 2009

How do I find the current machines full hostname in C (hostname and domain information)?

I was searching a easy method to get hostname , when i googled i got some info and here i added some of them and also some tried on my comp of my own , it may come handy sometime never know ;-)

To get a fully qualified name for a machine, we must first get the local hostname, and then lookup the canonical name.

The easiest way to do this is by first getting the local hostname using uname() or gethostname() and then performing a lookup with gethostbyname() and looking at the h_name member of the struct it returns. If you are using ANSI c, you must use uname() instead of gethostname().

Example:

char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
printf("Hostname: %s\n", hostname);
struct hostent* h;
h = gethostbyname(hostname);
printf("h_name: %s\n", h->h_name);
Unfortunately, gethostbyname() is deprecated in the current POSIX specification, as it doesn't play well with IPv6. A more modern version of this code would use getaddrinfo().

Example:

struct addrinfo hints, *info, *p;
int gai_result;

char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; /*either IPV4 or IPV6*/
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;

if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_result));
exit(1);
}

for(p = info; p != NULL; p = p->ai_next) {
printf("hostname: %s\n", p->ai_canonname);
}
Of course, this will only work if the machine has a FQDN to give - if not, the result of the getaddrinfo() ends up being the same as the unqualified hostname.

One more method to find hostname is using uname command
#uname -a [which is a command line utility]

If you want to use in prigram you can use uname() system call (I often use in my code)
#include

main()
{
struct utsname buf;
if ( uname(&buf) <>perror("uname");
printf(" hostname= %s ",buf.nodename);
}

uname is a very usefull system call it also provide info like
sysname,release ,version, (whatever you see when you execute uname -a command)

Hope it helps some one seeking for this , as I did ;-)