废话不说直接贴代码:
ip的数据结构
typedef struct ip_struct{
//ip地址划分后各个域的值
struct ipadress_struct
{
int first;
int second;
int third;
int forth;
}ipadress,*pipadress;
//ip地址
char szipadress[max_path];
//子网掩码
char szipmask[max_path];
ip_struct()
{
strcpy(szipadress,"");
strcpy(szipmask,"");
}
ip_struct(char szipadress[],char szipmask[])
{
strcpy(this->szipadress,szipadress);
strcpy(this->szipmask,szipmask);
}
}ip,*pip;
判断ip是否合理及获取ip各个域的值
bool judgeip(char *szip,ip_struct::ipadress_struct *ipadress)
{
if (!szip) return false;
int index=0;
int first=0,second=0,third=0,forth=0;
std::string ip=std::string(szip);
first=atoi(&ip[index]);
if (first>255)
return false;
if (ipadress)
ipadress->first=first;
index ;
index=ip.find_first_of('.',index);
second=atoi(&ip[ index]);
if(second>255)
return false;
if (ipadress)
ipadress->second=second;
index ;
index=ip.find_first_of('.',index);
third=atoi(&ip[ index]);
if(third>255)
return false;
if (ipadress)
ipadress->third=third;
index ;
index=ip.find_first_of('.',index);
forth=atoi(&ip[ index]);
if(forth>255)
return false;
if (ipadress)
ipadress->forth=forth;
return true;
}
判断是否同一网段
//-1 indicates ip格式错误,0表示不同网段,1表示同网段
int issamenetworksegment(char *szipadress,char *szmask,char *szipadresss1)
{
if (!szipadress||!szmask||!szipadresss1) return false;
ip_struct::ipadress_struct ip,ip1,mask;
if (judgeip(szipadress,&ip)&&judgeip(szipadresss1,&ip1)&&judgeip(szmask,&mask))
{
ip.first=ip.first & mask.first;
ip.second=ip.second & mask.second;
ip.third=ip.third & mask.third;
ip.forth=ip.forth & mask.forth;
ip1.first=ip1.first & mask.first;
ip1.second=ip1.second & mask.second;
ip1.third=ip1.third & mask.third;
ip1.forth=ip1.forth & mask.forth;
if(ip.first==ip1.first&&ip.second==ip1.second&&ip.third==ip1.third&&ip.forth==ip1.forth)
return 1;
else
return 0;
}
else
return -1;
}