Home »
C programs »
C advance programs
C program to Get Computer System IP Address in Linux
This program will read the IP Address of Linux System using C program.
Get IP Address in Linux using C program
/*C program to get IP Address of Linux Computer System.*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
int main()
{
unsigned char ip_address[15];
int fd;
struct ifreq ifr;
/*AF_INET - to define network interface IPv4*/
/*Creating soket for it.*/
fd = socket(AF_INET, SOCK_DGRAM, 0);
/*AF_INET - to define IPv4 Address type.*/
ifr.ifr_addr.sa_family = AF_INET;
/*eth0 - define the ifr_name - port name
where network attached.*/
memcpy(ifr.ifr_name, "eth0", IFNAMSIZ - 1);
/*Accessing network interface information by
passing address using ioctl.*/
ioctl(fd, SIOCGIFADDR, &ifr);
/*closing fd*/
close(fd);
/*Extract IP Address*/
strcpy(ip_address, inet_ntoa(((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr));
printf("System IP Address is: %s\n", ip_address);
return 0;
}
Output:
System IP Address is: 152.167.0.71
Code Explanation
1. struct ifreq
ifreq is basically used to configure Network Interface Devices. Firstly, we should provide ifreq to define the name of Interface Device.
This structure contains other structures too, but here we are using structure struct sockaddr ifr_addr.
This structure contains a member named sin_addr that stores ip address of the system
For detailed description about the Network Interfaces structures and functions click here.
2. inet_ntoa()
This function will convert and return the Ip address in array (character array/ string) format.
3. SIOCGIFFLAGS
Is a flag to get the active flag of the word.
C Advance Programs »