C++ program to set IP address, subnet mask, network gateway in Linux System

Learn: How to set network settings like IP Address, Subnet Mask, Network Gateway using C++ program in Linux System using G++ Compiler?

In our previous article, we have discussed about network settings. In this article we are going to learn how we can set network settings in Linux based systems using C++ program (this program is compiled and executed under G++ compiler).

Following Network settings will be applies through given program:

  1. IP Address
  2. Subnet Mask
  3. Gateway

Pointes to remember while writing this code:

  1. Use standard Linux commands to set network settings through C++ program, system() library function is used to execute these commands.
  2. Network interface must be used with the standard Linux command, here we are using "etho", which is the network interface is my system.
  3. Before executing any network related command, use link down command.
  4. After executing all command, use link up command.

Consider the program:

#include <iostream>
using namespace std;

#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>	

void setIPv4(char * ip,char * gw,char * netmask)
	char cmd[128];
	//network interface
	char nwkInf[5]="eth0";

	//link down command in Linux
	sprintf(cmd,"ip link set %s down",nwkInf);
	//command to set ip address, netmask
	sprintf(cmd,"ifconfig %s %s netmask %s",nwkInf,ip,netmask);
	printf("\ncmd : %s",cmd); fflush(stdout);

	//command to set gateway
	sprintf(cmd,"route add default gw %s %s",gw,nwkInf);

	//link up command
	sprintf(cmd,"ip link set %s up",nwkInf);

int main()
	//calling function to set network settings
	return 0;

Here, "" is IP Address, "" is Network Gateway, and "" is Subnet Mask.

Related Programs


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.