子网掩码转换为IP范围


子网掩码转换为IP范围
 
在网络应用中,经常需要将子网掩码转换为IP范围,以便进行进一步的计算.
以下是转换的原理及代码:  www.2cto.com  
一 子网掩码的作用, 就是将某个IP地址划分为'子网编号'和'主机地址'
   掩码格式       [子网编号:26bit               ]主机地址:6bit
   172.16.2.64/26 [10101100 00010000 00000010 01]000000
   172.16.2.96/26 [10101100 00010000 00000010 01]100000
   6bit的主机地址, 可以容纳63个编号. 则上面两个掩码的范围是
   掩码格式       IP范围
   172.16.2.64/26 [172.16.2.64 - 172.16.2.127]
   172.16.2.96/26 [172.16.2.96 - 172.16.2.127] *上一条的子集
 
二 算法  www.2cto.com  
typedef struct
{
u_int32_t min;
u_int32_t max;
}ip_range_t;
int str2iprange( ip_range_t *ipr, char *sipr)
{
char sip[16];
char smask[3];
sscanf( sipr, "%[^/]/%s", sip, smask);
ipr->min = ntohl(inet_addr( sip));
ipr->max = (ipr->min & ~( (0x1 << (32 - atoi(smask))) - 1)) + ( (0x1 << (32 - atoi(smask))) - 1);
}
三 测试  www.2cto.com  
ip_range_t ipr;
str2iprange( &ipr, "172.16.2.94/24");
struct in_addr min = { htonl( ipr.min)};
printf("%s - ", inet_ntoa( min));
struct in_addr max = { htonl( ipr.max)};
printf("%s \n", inet_ntoa( max));
输出结果:
172.16.2.94 - 172.16.2.127
END
 

相关内容

    暂无相关文章