关闭

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

2194人阅读 评论(0) 收藏 举报
分类:

首先问个问题: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);
       }


 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:23353次
    • 积分:648
    • 等级:
    • 排名:千里之外
    • 原创:40篇
    • 转载:6篇
    • 译文:1篇
    • 评论:1条