菜鸟笔记
提升您的技术认知

c++实现ip是否在同一个网段的判断

废话不说直接贴代码:

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;
}