I am trying to assign an IPv6 address for an interface using ioctl, but in vain. Here is the code I used:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <net/if.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/sockios.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define IFNAME "eth1"
#define HOST "fec2::22"
#define ifreq_offsetof(x) offsetof(struct ifreq, x)
int main(int argc, char **argv) {
struct ifreq ifr;
struct sockaddr_in6 sai;
int sockfd;
int selector;
unsigned char mask;
char *p;
sockfd = socket(AF_INET6, SOCK_DGRAM, 0);
if (sockfd == -1) {
printf("Bad fd\n");
return -1;
}
strncpy(ifr.ifr_name, IFNAME, IFNAMSIZ);
memset(&sai, 0, sizeof(struct sockaddr));
sai.sin6_family = AF_INET6;
sai.sin6_port = 0;
if(inet_pton(AF_INET6, HOST, (void *)&sai.sin6_addr) <= 0) {
printf("Bad address\n");
return -1;
}
p = (char *) &sai;
memcpy( (((char *)&ifr + ifreq_offsetof(ifr_addr) )),
p, sizeof(struct sockaddr));
int ret = ioctl(sockfd, SIOCSIFADDR, &ifr);
printf("ret: %d\terrno: %d\n", ret, errno);
ioctl(sockfd, SIOCGIFFLAGS, &ifr);
printf("ret: %d\terrno: %d\n", ret, errno);
ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
ioctl(sockfd, SIOCSIFFLAGS, &ifr);
printf("ret: %d\terrno: %d\n", ret, errno);
close(sockfd);
return 0;
}
ioctl causes a failure, stating ENODEV. When the socket family is changed to sockfd = socket(AF_INET, SOCK_DGRAM, 0);, calls will not be called again by EINVAL.
I managed to assign the IPv4 address to the interface to the code above using
sockaddr_ininstead sockaddr_in6.
Is it not possible to assign an IPv6 address using ioctl?
Maddy source
share