Home » C programs » Advance C programs

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*/
    close(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: 152.167.0.80
IP Address updated sucessfully. 
Updated IP Address is: 152.167.0.80

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*/
    system(command);
    
    printf("Ip updated sucessfully.\n");
    
    return 0;
}
Enter Ip Address: 152.167.0.80
Ip updated sucessfully.





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.