Assign ipv6 address using ioctl

前端 未结 2 1621
野性不改
野性不改 2020-12-10 18:44

I\'m trying to assign an IPv6 address to an interface using ioctl, but in vain. Here\'s the code I used:

#include 
#include 
#i         


        
2条回答
  •  被撕碎了的回忆
    2020-12-10 19:21

    Drawing inspiration from the linux implementation of 'ifconfig' command, I was able to set the IPv6 address on an interface. Here's the code for it:

    #include 
    #include 
    #include 
    #include 
    #include              
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #if __GLIBC__ >=2 && __GLIBC_MINOR >= 1
    #include 
    #include 
    #else
    #include 
    #include 
    #endif
    
    #define IFNAME "eth0"
    #define HOST "fec2::22"
    #define ifreq_offsetof(x)  offsetof(struct ifreq, x)
    
    struct in6_ifreq {
        struct in6_addr ifr6_addr;
        __u32 ifr6_prefixlen;
        unsigned int ifr6_ifindex;
    };
    
    int main(int argc, char **argv) {
    
        struct ifreq ifr;
        struct sockaddr_in6 sai;
        int sockfd;                     
        struct in6_ifreq ifr6;
    
        sockfd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_IP);
        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_pton(AF_INET6, HOST, (void *)&sai.sin6_addr) <= 0) {
            printf("Bad address\n");
            return -1;
        }
    
        memcpy((char *) &ifr6.ifr6_addr, (char *) &sai.sin6_addr,
                   sizeof(struct in6_addr));
    
        if (ioctl(sockfd, SIOGIFINDEX, &ifr) < 0) {
            perror("SIOGIFINDEX");
        }
        ifr6.ifr6_ifindex = ifr.ifr_ifindex;
        ifr6.ifr6_prefixlen = 64;
        if (ioctl(sockfd, SIOCSIFADDR, &ifr6) < 0) {
            perror("SIOCSIFADDR");
        }
    
        ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
    
        int ret = ioctl(sockfd, SIOCSIFFLAGS, &ifr);
        printf("ret: %d\terrno: %d\n", ret, errno);
    
        close(sockfd);
        return 0;
    }
    

提交回复
热议问题