Home »
C++ programs »
C++ Most popular & searched programs
C++ program to set network settings for IPv6 Network in Linux Devices
Learn: How to set network settings for IPv6 based Network in Linux Devices? Here, we will learn to set IP address, prefix and Gateway for IPv6 based Network.
[Last updated : February 26, 2023]
If you are not aware with the series of IPv6 based network, I would suggest to read: What is IPv6 protocol?
Here, we are going to learn how to configure/set IPv6 based network settings like IP address, prefix value and Gateway using a C++ program in Linux based devices. This program is compiled and executed under G++ compiler.
Setting the network settings for IPv6 Network in Linux Devices
Using given program, we will set following information:
- IP Address
- Prefix
- Gateway
All above settings will be applied on network interface like : Here at my system, network interface is: eth0.
Points to remember:
- We are executing Linux terminal commands in C++ program using system() function
- To set IPv6 based settings, we need to flush network interface
- Execute command for link down
- Execute command to set IP address
- Execute command to set IP address and Prefix
- Execute command to set Gateway
- Execute command for link up
C++ code to set the network settings for IPv6 Network in Linux Devices
#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>
//function to set IPv6 and Gateway
void setIPv6(char * ip,unsigned int prefix,char * gateway)
{
char cmd[128]={0};
char nwkInf[5]="eth0";
sprintf(cmd,"ip addr flush dev %s",nwkInf);
system(cmd);
memset(cmd,0x00,128);
sprintf(cmd,"ip link set %s down",nwkInf);
system(cmd);
memset(cmd,0x00,128);
sprintf(cmd,"/sbin/ip -6 addr add %s/%d dev %s",ip,prefix,nwkInf);
system(cmd);
memset(cmd,0x00,128);
sprintf(cmd,"/sbin/route -A inet6 add default gw %s",gateway);
system(cmd);
memset(cmd,0x00,128);
sprintf(cmd,"ip link set %s up",nwkInf);
system(cmd);
}
//main program
int main()
{
//passing IPv6,prefix and Gateway
setIPv6("fd18:6dc5:3dbc:ce24::5",64,"fd18:6dc5:3dbc:ce24::1");
return 0;
}
Here, "fd18:6dc5:3dbc:ce24::5" is IP Address, 64 is prefix value and "fd18:6dc5:3dbc:ce24::1" Gateway.