0

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

MD XF
  • 7,860
  • 7
  • 40
  • 71
  • 1
    Which operating system? And why do you do this? – Basile Starynkevitch Mar 01 '16 at 13:21
  • Way too many dependencies from external factors to provide an answer - You might have DHCP activated, in that case it isn't even decided on your computer what IP adress it is going to receive. – tofro Mar 01 '16 at 13:40
  • 1
    Possible duplicate of [How to set the IP address from C in linux](http://stackoverflow.com/questions/6652384/how-to-set-the-ip-address-from-c-in-linux) – a3f Mar 01 '16 at 13:46
  • This might help you, too: http://stackoverflow.com/questions/5308090/set-ip-address-using-siocsifaddr-ioctl – Ctx Mar 01 '16 at 14:11
  • You example updated IP address is a multicast address, and you are not allowed to assign it to an interface. Multicast addresses cannot be source addresses, as would be the case with assigning one to an interface. – Ron Maupin Mar 09 '17 at 21:54

1 Answers1

0

You're already using ioctl(SIOCGIFADDR to get the interface address, so once you change it in ifreq struct, you can then do ioctl(SIOCSIFADDR to set it. Unsuprisingly, that's what the G and S characters mean the ioctl names (get and set).

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226