Here is the source code of the program in C to get the local IP address. This program is successfully compiled, and the output is also given below.

C program to get local IP Address

#include<stdlib.h>
#include<hostname>
#include <stdio.h>
struct hostent *he_bool;

struct in_addr a;

 
int
main (int argc) 
{
  
char *hostname = malloc (MAXHOSTNAMELEN);
  
memset (hostname, 0, MAXHOSTNAMELEN);
  
gethostname (hostname, MAXHOSTNAMELEN);
  
printf ("\nHost Name = %s ", hostname);
  
h_bool = gethostbyname (hostname);
  
if (h_bool)
    
    {
      
printf ("\nName: %s", h_bool->h_name);
      
while (*he->h_aliases)
	
printf ("\nAlias: %s", *h_bool->h_aliases++);
      
while (*h_bool->h_addr_list)
	
	{
	  
bcopy (*h_bool->h_addr_list++, (char *) &a, sizeof (a));
	  
printf ("\nIP Address: %s", inet_ntoa (a));
	
}
    
}
  
Else 
  {
    
printf ("\nError, Hostname is Not found! Please Try Agaian");
  
}
  
return 0;

}


 

Output

Name: TPPC
Alias: TPPC
IP Address: 119:150:189:35

Program Explanation

This program is written by using structures. The structures which are used in this program are:

struct hostent *he_bool;
struct in_addr a;

Every program starts execution from the main function. We declared and initialized a char pointer and use malloc function to get the hostname and store it into pointer hostname. Malloc is a built-in function in c to allocate the memory in a heap.

Malloc Function accesses the memory block via a pointer that malloc retunes. Then we use memset() by passing arguments. IsMemset is also a builtin function use to fill the memory block with any particular value.

Above next, we call a function gethostbyname(), which returns hostname and store it into the he_bool variable. Then we use the if-else statement; if he_bool is true then ‘If’ part will be executed. Otherwise ‘else’ part will run and an error message will be shown.

In the ‘if’ part, name of the host is printed and two while loops are applied. After writing hostname, a while loop is executed until he->address. In next while loop, IP address is computed and printed on the screen.

Related Articles

Last modified: May 5, 2019