我正在尝试使用ioctl为接口分配IPv6地址,但是徒劳无功.这是我使用的代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#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; /* socket fd we use to manipulate stuff with */
int selector;
unsigned char mask;
char *p;
/* Create a channel to the NET kernel. */
sockfd = socket(AF_INET6, SOCK_DGRAM, 0);
if (sockfd == -1) {
printf("Bad fd\n");
return -1;
}
/* get interface name */
strncpy(ifr.ifr_name, IFNAME, IFNAMSIZ);
memset(&sai, 0, sizeof(struct sockaddr));
sai.sin6_family = AF_INET6;
sai.sin6_port = 0;
//if(inet_aton(HOST, &sai.sin_addr.s_addr) == 0) {
if(inet_pton(AF_INET6, HOST, (void *)&sai.sin6_addr) <= 0) {
//&((struct sockaddr_in*)&sa)->sin_addr
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;
// ifr.ifr_flags &= ~selector; // unset something
ioctl(sockfd, SIOCSIFFLAGS, &ifr);
printf("ret: %d\terrno: %d\n", ret, errno);
close(sockfd);
return 0;
}
ioctl调用失败说ENODEV.当套接字的族更改为sockfd = socket(AF_INET,SOCK_DGRAM,0);时,调用再次失败,说EINVAL.
我可以使用上面的代码为接口分配IPv4地址
sockaddr_in代替sockaddr_in6.
是否无法使用ioctl分配IPv6地址?