×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object 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?
[Last updated : February 26, 2023]

Setting the IP address, subnet mask, network gateway in Linux System using C++ Program

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.

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

#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.

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.