Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15076
  • 博文数量: 1
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 20
  • 用 户 组: 普通用户
  • 注册时间: 2016-06-18 19:01
文章分类

全部博文(1)

文章存档

2018年(1)

分类: LINUX

2018-07-10 19:28:10

想法:把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;
}
阅读(1799) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:没有了

给主人留下些什么吧!~~