前缀长度转成子网掩码
原文地址:https://www.cnblogs.com/liqinglucky/p/ipv6_mask.html
将前缀长度转成子网掩码
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
int mask_fun(int mask_num)
{
int i,j, a, b;
unsigned char ipv6[16] = {0};
unsigned char ipv6_b[16] = {0};
unsigned char tmp_str[128] = {0};
a = mask_num / 8;
b = mask_num % 8;
for(i = 0; i < a; i++) {
ipv6[i] = 0xff;
}
for (j = 0; j < b; j++) {
ipv6[i] |= 0x80 >> j;
}
for (i = 0; i < 16; i++){
printf("ipv6[%d]:%x \n",15-i, ipv6[15-i]);
}
printf("\n===========================\n");
inet_ntop(AF_INET6,ipv6, tmp_str, sizeof(tmp_str));
printf("\nsubnet mask : %s \n", tmp_str);
return 1;
}
int main(int argc, char * argv[])
{
int mask_num;
if(argc != 2) {
printf("%s <mask_bit_num>\n", argv[0]);
return -1;
}
mask_num = atoi(argv[1]);
mask_fun( mask_num);
return 1;
}
运行结果
$ ./mask 80 ipv6[15]:0 ipv6[14]:0 ipv6[13]:0 ipv6[12]:0 ipv6[11]:0 ipv6[10]:0 ipv6[9]:ff ipv6[8]:ff ipv6[7]:ff ipv6[6]:ff ipv6[5]:ff ipv6[4]:ff ipv6[3]:ff ipv6[2]:ff ipv6[1]:ff ipv6[0]:ff =========================== subnet mask : ffff:ffff:ffff:ffff:ffff::