想法:把IP字符串转换为unsigned long类型的16进制数值,通过与掩码相与求得网段,判断网段是否相等即求得结果。
参考代码如下
#include
#include
#include
#include
//IP掩码位数
int SubnetBit(char *subnetmask)
{
int i;
int tmp=0xf8;
int bitNum;
unsigned char and;
char *token = NULL;
bitNum=0;
for (token = strtok (subnetmask, "."); token != NULL; token = strtok (NULL, ".")) {
tmp = atoi(token);
and=0x80;
for(i=0; i<8; i++) {
if(tmp & and)
bitNum+=1;
else
break;
and=and>>1;
}
}
//printf("bitNum:%d\n", bitNum);
return bitNum;
}
//判断ip_a与ip_b是否在同一网段
int same_subnet(char *subnetmask, char *ip_a, char *ip_b)
{
int i=3;
int ALL_BIT=32; /* ip address have 32 bits */
char *token = NULL;
unsigned long tmp = 0;
unsigned long cnt_a = 0;
unsigned long cnt_b = 0;
unsigned long mask = 0xFFFFFFFF;
int sub_mask=SubnetBit(subnetmask);
mask = mask << (ALL_BIT - sub_mask);
printf ("mask:%0x\n", mask);
for (token = strtok (ip_a, "."); token != NULL; token = strtok (NULL, ".")) {
tmp = atoi (token);
cnt_a += tmp<<(i<<3);
i--;
}
i = 3; /* reset i */
for (token = strtok (ip_b, "."); token != NULL; token = strtok (NULL, ".")) {
tmp = atoi (token);
cnt_b += tmp<<(i<<3);
i--;
}
//printf ("mask_a %x\tmask_b %x\n", cnt_a, cnt_b);
cnt_a &= mask; /* get the ip's netmask for compare */
cnt_b &= mask;
//printf ("mask_a %x\tmask_b %x\n", cnt_a, cnt_b);
if (cnt_a == cnt_b)
return 0;
else
return -1;
}
/*
** test code
*/
int main (int argc, char **argv)
{
int i;
if(argc<3){
return -1;
}
i= same_subnet (argv[1], argv[2], argv[3]);
printf ("%s subnet\n", i == 0? "same":"not same");
return 0;
}
阅读(2154) | 评论(0) | 转发(0) |