Q:

C program to Get Computer System IP Address in Linux

0

C program to Get Computer System IP Address in Linux

This program will read the IP Address of Linux System using C program.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C language important programs ( Advance Programs )

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
fork() function explanation and examples in Linux ... >>
<< C program to Set Computer System IP Address in Lin...