Can I set IP Address from code?

Hello,

I would like to set (and change) my IP address from a program - without
using the exec*, spawn* or system calls. Does someone have an example of
how to do this?

Thank You,
Ian.

Ian Todd <info@ndt.ca> wrote:

Hello,

I would like to set (and change) my IP address from a program - without
using the exec*, spawn* or system calls. Does someone have an example of
how to do this?

Thank You,
Ian.

Something like the following. You can use SIOCDIFADDR to delete.

Regards,

-seanb



#include <sys/socket.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdio.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>


int
main(void)
{
int s;
struct ifreq ifreq;
struct sockaddr_in *sa_in;

if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror(“socket”);
return EXIT_FAILURE;
}

memset(&ifreq, 0x00, sizeof(ifreq));

strcpy(ifreq.ifr_name, “en0”);

sa_in = (struct sockaddr_in *)&ifreq.ifr_addr;

sa_in->sin_family = AF_INET;
sa_in->sin_len = sizeof(*sa_in);
sa_in->sin_addr.s_addr = htonl(0x0a000001);

if (ioctl(s, SIOCSIFADDR, &ifreq) == -1) {
perror(“ioctl”);
return EXIT_FAILURE;
}

return EXIT_SUCCESS;
}