i have a hard code(C code) to print my computer IP address, i'll alter my IP with some requirements and finally i can print the updated IP on screen. now the problem is, i need to set the altered IP address to my computer. anyone please help me in setting a new IP address to a computer using C language as platform. my hard code and its output is attached below.
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <unistd.h>
#include <arpa/inet.h>
int main()
{
int n,chain=2,ADU=2,cam_port=2,IP=0,formulae,stream_num=3;
struct ifreq ifr;
char array[] = "eth0";
int int_val = 0;
int c = 0;
char *some_addr;
n = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name , array , IFNAMSIZ - 1);
ioctl(n, SIOCGIFADDR, &ifr);
close(n);
printf("IP Address is %s - %s\n" , array , inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr) );
some_addr = inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr);
printf("The last character octet is %c%c%c\n", some_addr[11],some_addr[12],some_addr[13]);
for (c = 11; some_addr[c]!= '\0'; c++)
{
int_val = int_val * 10 + some_addr[c] - '0';
}
printf("int value = %d\n", int_val);
IP = int_val;
formulae=((chain-1)*128) + ((ADU-1)*32) + ((cam_port-1)*4) + (stream_num+1);
IP=formulae;
printf("updated IP is 239.192.140.%d\n",IP);
return 0;
}
output:
IP Address is eth0 - 192.168.15.91
The last character octet is 91
int value = 91
updated IP is 239.192.140.168