Home » C++ programs » C++ Most popular & searched programs

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);
	system(cmd); 
	
	
	memset(cmd,0x00,64);
	//command to set ip address, netmask
	sprintf(cmd,"ifconfig %s %s netmask %s",nwkInf,ip,netmask);
	system(cmd);	 
	printf("\ncmd : %s",cmd); fflush(stdout);
	memset(cmd,0X00,64);

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

	memset(cmd,0X00,64);
	//link up command
	sprintf(cmd,"ip link set %s up",nwkInf);
	system(cmd); 
	
}

int main()
{
	//calling function to set network settings
	setIPv4("192.168.10.216","192.168.10.1","255.255.255.0");
	return 0;
}

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






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





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.