C语言 根据掩码计算网段的起止ip
原文地址:https://www.yuque.com/docs/share/85a26263-484a-42f6-880b-2b511ae1bd20?#
根据ipv4掩码计算
#include <stdio.h> #include <arpa/inet.h> #define uint8_t unsigned char #define uint32_t unsigned int int main(int argc,char **argv) { // 1.1.0.0/16的网段 uint32_t ipv4 = 0x1010000; uint8_t prefix = 16; uint32_t shift_bits = 32 - prefix; uint32_t host_ipv4 = ipv4 >> shift_bits; //网络段 1.1.0.0是不变的 host_ipv4++; //先算出下一个网段 0x102 //1.1.0.0网段最后一个地址是0x1020000 -1 uint32_t end_ipv4 = (host_ipv4<<shift_bits)-1; // 101ffff printf("start ip: %x end ip: %x\n",ipv4,end_ipv4); end_ipv4 = htonl(end_ipv4); // ffff0101 char ip_str[20]={0}; inet_ntop(AF_INET, &end_ipv4, ip_str, INET_ADDRSTRLEN); // 1.1.255.255 printf("end ip: %s \n",ip_str); return 0; }
运行结果
$ gcc -o ip_calculator ip_calculator.c $ ./ip_calculator start ip: 1010000 end ip: 101ffff end ip: 1.1.255.255
根据ipv6掩码计算
#include <stdio.h> #include <arpa/inet.h> #define uint8_t unsigned char #define uint32_t unsigned int int main(int argc,char **argv) { uint8_t ipv6[16]={0}; char IPdotdec[46]="1:1:1:eeff::"; inet_pton(AF_INET6, IPdotdec, (void *)&ipv6); printf("十六进制 : %s \n",IPdotdec); uint8_t prefix = 54; uint32_t shift_bits = 128 - prefix; uint32_t total_shift_byte,remain_shift_bits,j; uint8_t host_ipv6 = 0, host2_ipv6 = 0,host_max = 0xFF; uint8_t host_ipv6_str = 0; uint8_t reach_host_max = 0; total_shift_byte = shift_bits/8; //6 remain_shift_bits = shift_bits%8; //6 for(j = 0; j < total_shift_byte+1; j++) { if(j < total_shift_byte){ //e.g. prefix_len = 48. addr[0] ~ [5] is fixed,addr[6]~[15] is variable init to 0 ipv6[15-j] = 0xff; } else if(remain_shift_bits) { //just parts of this byte shitf to 0 host_ipv6 = ipv6[15-j]>> remain_shift_bits; host_ipv6++; host_ipv6 = (host_ipv6<<remain_shift_bits)-1; ipv6[15-j]= host_ipv6 ; break; // find the fix addr[15-j],case 1:just 1 byte affected } printf("ipv6[%u]:0x%x %x remain_shitf %u\n",15-j,ipv6[15-j],host_ipv6,remain_shift_bits); } char ipv6_str1[46]={0}; inet_ntop(AF_INET6,ipv6, ipv6_str1,INET6_ADDRSTRLEN); printf("ip %s, shift addr[%u]\n", ipv6_str1, 15-j); return 0; }
运行结果:
$ ./ipv6_calculator 十六进制 : 1:1:1:eeff:: ipv6[15]:0xff 0 remain_shitf 2 ipv6[14]:0xff 0 remain_shitf 2 ipv6[13]:0xff 0 remain_shitf 2 ipv6[12]:0xff 0 remain_shitf 2 ipv6[11]:0xff 0 remain_shitf 2 ipv6[10]:0xff 0 remain_shitf 2 ipv6[9]:0xff 0 remain_shitf 2 ipv6[8]:0xff 0 remain_shitf 2 ipv6[7]:0xff 0 remain_shitf 2 ip 1:1:1:efff:ffff:ffff:ffff:ffff, shift addr[6]