如何获取当前配置的IPV6地址的前缀长度(掩码)

首先问个问题:IPV6是否有掩码?

答: 有

 

GOOGLE上查了一圈没有找到好的方法,字节摸索了一套可行的方法,同分享:

下述程序打印处掩码长度,由此判断前缀长度,good!

 

       #include <sys/socket.h>
       #include <netdb.h>
       #include <ifaddrs.h>
       #include <stdio.h>
       #include <stdlib.h>
       #include <unistd.h>
       #include <net/if.h>
       #include <netinet/in.h>
        #include <sys/types.h>


       int
       main(int argc, char *argv[])
       {
           struct ifaddrs *ifaddr, *ifa;
           int family, s;
           char host[NI_MAXHOST];
	   char host_netmask[NI_MAXHOST];
	
	   struct sockaddr_in6  *pip6 = NULL;
           int i;

           if (getifaddrs(&ifaddr) == -1) {
               perror("getifaddrs");
               exit(EXIT_FAILURE);
           }

           /* Walk through linked list, maintaining head pointer so we
              can free list later */

           for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
               if (ifa->ifa_addr == NULL)
                   continue;

               family = ifa->ifa_addr->sa_family;

               /* Display interface name and family (including symbolic
                  form of the latter for the common families) */

               printf("%s  address family: %d%s\n",
                       ifa->ifa_name, family,
                       (family == AF_PACKET) ? " (AF_PACKET)" :
                       (family == AF_INET) ?   " (AF_INET)" :
                       (family == AF_INET6) ?  " (AF_INET6)" : "");

               /* For an AF_INET* interface address, display the address */

               if (family == AF_INET || family == AF_INET6) {
                   s = getnameinfo(ifa->ifa_addr,
                           (family == AF_INET) ? sizeof(struct sockaddr_in) :
                                                 sizeof(struct sockaddr_in6),
                           host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
                   if (s != 0) {
                       printf("getnameinfo() failed: %s\n", gai_strerror(s));
                       exit(EXIT_FAILURE);
                   }
		   getnameinfo(ifa->ifa_netmask,
                               (family == AF_INET)? sizeof(struct sockaddr_in): sizeof(struct sockaddr_in6),
                                host_netmask, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
		   if(AF_INET6==family)
		   {
			pip6 = (struct sockaddr_in6 *)(ifa->ifa_netmask);
			char *p = (char *)&(pip6->sin6_addr);
                        for(i=0;i<16;i++)
                        {
				printf("%d ",*p);
				p++;
			}
		   }

                   printf("\taddress: <%s>\n", host);
                   printf("\tnetmaks: <%s>\n", host_netmask);
               }
           }

           freeifaddrs(ifaddr);
           exit(EXIT_SUCCESS);
       }


 

阅读更多
个人分类: 杂项
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭