PROGRAM TO DISPLAY IP ADDRESS OF THE SYSTEM

 In this example,  you will learn a program to display the IP address of the system.


IP Address:

An IP (Internet Protocol) address is an identifier assigned to each computer and other device (ex. router, mobile etc)connected to IP network that is used to locate and identify the node in the communication with other nodes on the network.


Program:

//Program to display IP address of the system

#include<stdio.h>
#include<string.h>

#include<sys/types.h>

#include<sys/socket.h> 

#include<sys/ioctl.h>

#include<netinet/in.h>

#include<net/if.h> 

#include<unistd.h> 

#include<arpa/inet.h> 


int main( )
{
int n;
struct ifreq ifr;
char array[] = "eth0";
n = socket(AF_INET, SOCK_DGRAM, 0);

//Type of address to retrieve - IPv4 IP address

ifr.ifr_addr.sa_family = AF_INET;

//Copy the interface name in the ifreq structure
strncpy(ifr.ifr_name , array , IFNAMSIZ - 1);
ioctl(n, SIOCGIFADDR, &ifr);
close(n);

//display result
printf("IP Address is %s - %s\n" , array , inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr) );

return 0;
}


Output:


IP Address is eth0 - 172.17.0.29



So that's it ! Just try this code by your own. If you have any doubts then feel free to drop a comment . I'll be happy to answer your questions .

Keep coding....

Comments

Popular posts from this blog

DECIMAL TO OCTAL CONVERSION IN C

PROGRAM TO CONVERT BINARY CODE TO GRAY CODE

KRISHNMURTHY NUMBER PROGRAM IN C