IPv4掩码与掩码位数的转换

1. 根据掩码获取掩码的位数 int mask2len(unsigned int mask) { /*eg: 255.255.255.0 255.0.255.255.0*/ int bit=0,len=0; while( ~mask & (1ULL<<bit)) bit++; len = 32 - bit; if(~mask >> bit){ printf("mask is not standerd, get mask length error\n"); return -1; } printf("mask:%8.8x len=%d\n", mask, len); return len; } 2. 根据掩码位数获取验码 int len2mask(int len, unsigned int *mask) { unsigned int maskwild = 0; if(len<0 || len>32) return -1; int hostbits=32-len; while(hostbits--){ maskwild=(maskwild << 1) + 1; } maskwild=~maskwild; if(mask){ *mask = maskwild; } printf("mask len is %d, and mask is %8.8x\n", len, maskwild); #if 0 struct in_addr ip; ip.s_addr=htonl(maskwild); printf("mask len is %d, and mask is %s\n", len, inet_ntoa(ip)); #endif return 0; } 3. 测试结果 void main(int argc, char *argv[]) { len2mask(9, NULL); len2mask(15, NULL); len2mask(24, NULL); len2mask(28, NULL); len2mask(30, NULL); len2mask(32, NULL); len2mask(34, NULL); mask2len(0x80000000); mask2len(0xffff0000); mask2len(0xfffff000); mask2len(0xffffff00); mask2len(0xfffffff0); mask2len(0xfffffffc); mask2len(0x12345678); }

编译后运行,结果如下:

root@ubantu:/mnt/hgfs/em嵌入式学习记录/schedule调度器# ./demo.out mask len is 9, and mask is ff800000 mask len is 15, and mask is fffe0000 mask len is 24, and mask is ffffff00 mask len is 28, and mask is fffffff0 mask len is 30, and mask is fffffffc mask len is 32, and mask is ffffffff mask:80000000 len=1 mask:ffff0000 len=16 mask:fffff000 len=20 mask:ffffff00 len=24 mask:fffffff0 len=28 mask:fffffffc len=30 mask is not standerd, get mask length error root@ubantu:/mnt/hgfs/em嵌入式学习记录/schedule调度器#

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzgxpp.html