C program to Set Computer System IP Address in Linux

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

Set IP Address in Linux using C program

/*C program to set 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;
    struct sockaddr_in* addr;

    /*Read IP Address*/
    printf("Enter Ip Address: ");
    scanf("%s", ip_address);

    /*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);

    /*defining the sockaddr_in*/
    addr = (struct sockaddr_in*)&ifr.ifr_addr;

    /*convert ip address in correct format to write*/
    inet_pton(AF_INET, ip_address, &addr->sin_addr);

    /*Setting the Ip Address using ioctl*/
    ioctl(fd, SIOCSIFADDR, &ifr);
    /*closing fd*/

    printf("IP Address updated sucessfully.\n");

    /*Getting the Ip Address after Updating.*/

    /*clear ip_address buffer with 0x20- space*/
    memset((unsigned char*)ip_address, 0x20, 15);
    ioctl(fd, SIOCGIFADDR, &ifr);
    /*Extracting Ip Address*/
    strcpy(ip_address, inet_ntoa(((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr));

    printf("Updated IP Address is: %s\n", ip_address);

    return 0;


Enter Ip Address:
IP Address updated sucessfully. 
Updated IP Address is:

The details of the functions and structures in the previous program – C program to Get the IP Address of the Linux System.

Using system()

#include <stdio.h>
#include <stdlib.h> /*for system function*/

/*define port name where network attached*/
#define ifr_name "eth0"

int main()
    unsigned char ip_address[15], command[100];

    printf("Enter Ip address: ");
    scanf("%s", ip_address);

    /*make command*/
    sprintf((char*)command, "ifconfig %s %s", ifr_name, ip_address);

    /*run command*/

    printf("Ip updated sucessfully.\n");

    return 0;


Enter Ip Address:
Ip updated sucessfully.

C Advance Programs »

Related Programs


Top MCQs

Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.