#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
bool Addr_to_Array(char* addr, int* array)
{
bool ret = (addr != NULL );
char* sub = NULL;
int i = 0;
if( ret)
{
sub = strtok(addr,"."); // 分割字符串
while(sub != NULL)
{
array[i] = atoi(sub); // 字符串变为整数
i++;
sub = strtok(NULL,".");
}
}
return ret;
}
int checkNetSegment(char* mask_addr, char* ip1_addr, char* ip2_addr)
{
bool ret = true;
int add[4] = {0};
int p1[4] = {0};
int p2[4] = {0};
ret = ret && Addr_to_Array(mask_addr, add);
ret = ret && Addr_to_Array(ip1_addr, p1);
ret = ret && Addr_to_Array(ip2_addr, p2);
if(ret)
{
for(int i=0; i<4; i++)
{
if( (p1[i] & add[i]) == (p2[i] & add[i]) )
{
if( i == 3)
{
//cout << "ip1 and ip2 are in the same netsegment." << endl;
}
continue;
}
else
{
//cout << "ip1 and ip2 are not in the same netsegment." << endl;
ret = false;
break;
}
}
}
return ret; //static_cast<int>(ret);
}
int main()
{
char mask_addr[] = "255.255.255.0";
char ip1_addr[] = "192.168.1.120";
char ip2_addr[] = "192.168.1.128";
int ret = checkNetSegment(mask_addr, ip1_addr, ip2_addr);
if( 1 == ret )
{
cout << "ip1 and ip2 are in the same netsegment." << endl;
}
else
{
cout << "ip1 and ip2 are not in the same netsegment." << endl;
}
return 0;
}