Home » C programs » Advance C 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*/
    /*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;
    System IP Address is:

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.


This function will convert and return the Ip address in array (character array/ string) format.


Is a flag to get the active flag of the word.

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.