An Internet Protocol address (IP address) is a numerical label assigned to each device connected to a computer network that uses the Internet Protocol for communication.


  1. Create array hostbuffer[256], char *IPBuffer, struct hostent *host_entry,hostname
  2. hostname = gethostname(hostbuffer, sizeof(hostbuffer)) 
  3. hostnamechk(hostname)  

    host_entry = gethostbyname(hostbuffer)    ( To get host info) 


  4. IPbuffer = inet_ntoa(*((struct in_addr*)host_entry->h_addr_list[0]))  (Converts Internet network address to ASCII string) 


// C program to print 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 hostnamechk(int hostname) 


     if (hostname == -1) 







// getting host information of the host name 

void hostentrychk(struct hostent * hostentry) 


     if (hostentry == NULL) 







// Converting space-delimited IPv4 address 

// to dotted-decimal format 

void ipbufferchk(char *IPbuffer) 


     if (NULL == IPbuffer) 







// Driver code 

int main() 


     char hostbuffer[256]; 

     char *IPbuffer; 

     struct hostent *host_entry; 

     int hostname; 


     hostname = gethostname(hostbuffer, sizeof(hostbuffer)); 


     // To get host information 

     host_entry = gethostbyname(hostbuffer); 



     // Converting Internet network address to ASCII string 

     IPbuffer = inet_ntoa(*((struct in_addr*)host_entry->h_addr_list[0])); 

     printf("Host IP: %s", IPbuffer); 

     return 0; 


Use of terms used

  1. The <unistd.h> header defines miscellaneous symbolic constants and types, and declares miscellaneous functions.
  2. <errno.h> is a header file in the standard library of the C programming language. It defines macros for reporting and retrieving error conditions using the symbol errno.
  3. The <netdb.h> header shall define the hostent structure
  4. The <netinet/in. h> header also defines the IN6ADDR_ANY_INIT macro. This macro must be constant at compile time and can be used to initialize a variable of type struct in6_addr to the IPv6 wildcard address. This variable is initialized by the system to contain the loopback IPv6 address.
  5. <arpa/inet.h> – definitions for internet operations
  6. The inet_ntoa() function converts the specified Internet host address to a string in the Internet standard dot notation.
  7. perror is used in C and C++ to print an error message to stderr.


Report Error/ Suggestion

Related Posts:

CopyRight © 2020

CopyRight © 2020