Display hostname and IP address in C

by
Ryan
on
October 18, 2008

Here is a good way to determine the hostname and IP address of the local machine in C.

You first have to grab the hostname with gethostname().

char hostbuf[256];
gethostname(hostbuf,sizeof(hostbuf));

Take the hostname and use it to grab the hostent struct with gethostbyname().

struct hostent *hostentry;
hostentry = gethostbyname(hostbuf);

Finally you have to take the hostent that is returned and pull out the IP address. It is in network byte order, so you have to convert it to a string with inet_ntoa().

char * ipbuf;
ipbuf = inet_ntoa(*((struct in_addr *)hostentry->h_addr_list[0]));

Put all this together into a working programs.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
        char hostbuf[256];
        char * ipbuf;
        struct hostent *hostentry;
        int ret;

        ret = gethostname(hostbuf,sizeof(hostbuf));

        if(-1 == ret){
                perror("gethostname");
                exit(1);
        }

        hostentry = gethostbyname(hostbuf);

        if(NULL == hostentry){
                perror("gethostbyname");
                exit(1);
        }

        ipbuf = inet_ntoa(*((struct in_addr *)hostentry->h_addr_list[0]));

        if(NULL == ipbuf){
                perror("inet_ntoa");
                exit(1);
        }

        printf("Hostname: %s Host IP: %s\n", hostbuf, ipbuf);

        return 0;
}
3 Comments
C
, , , , , , ,

No related posts.

Comments (3)

dude, this program seg faults. could you post some working code please?

my bad, i was using it incorrectly. it works, thanks.

    Glad I could help!

Trackbacks (0)

No trackbacks yet

Leave a Comment

(displayed with your post)
(will not be published)
(optional)
Copyright 2008-2010 WiredRevolution.com. All rights reserved.