C Program to display hostname and IP address

There are many ways to find Hostname and IP address of a local machine. Here is a simple method to find hostname and IP address using C program.

We will be using the following functions :-

gethostname() : The gethostname function retrieves the standard host name for the local computer.

gethostbyname() : The gethostbyname function retrieves host information corresponding to a host name from a host database.

inet_ntoa() : The inet_ntoa function converts an (Ipv4) Internet network address into an ASCII string in Internet standard dotted-decimal format.






// C program to display hostname
// and IP address
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
// Returns hostname for the local computer
void checkHostName(int hostname)
    if (hostname == -1)
// Returns host information corresponding to host name
void checkHostEntry(struct hostent * hostentry)
    if (hostentry == NULL)
// Converts space-delimited IPv4 addresses
// to dotted-decimal format
void checkIPbuffer(char *IPbuffer)
    if (NULL == IPbuffer)
// Driver code
int main()
    char hostbuffer[256];
    char *IPbuffer;
    struct hostent *host_entry;
    int hostname;
    // To retrieve hostname
    hostname = gethostname(hostbuffer, sizeof(hostbuffer));
    // To retrieve host information
    host_entry = gethostbyname(hostbuffer);
    // To convert an Internet network
    // address into ASCII string
    IPbuffer = inet_ntoa(*((struct in_addr*)
    printf("Hostname: %s\n", hostbuffer);
    printf("Host IP: %s", IPbuffer);
    return 0;



Hostname: cContainer
Host IP:

Output varies machine to machine

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.