}
}
return;
else{ }
if(strlen(argv[1])>18){ //先判断最简单的错误,长度是否超出 }
if(strlen(argv[2])>15){ }
ipTest test(argv[1],argv[2]); //实例话ipTest类
test.print(); //完成相应判别并输出结果
cout<<\return;
cout<<\return;
//构造函数
ipTest::ipTest( char* subnetPlusMask, char *ip){
maskIsValid=true; char temp[2];
//把'/'前的字符复制到subnet字符数组中 int smLen=strlen(subnetPlusMask);
for( int i=0; i subnet[i]='\\0'; Tempsub[i]='\\0'; if(i<=smLen-2){ //初始化mask和maskIsVslid if(i==smLen-2){ temp[0]=subnetPlusMask[i+1]; this->subnet[i]=subnetPlusMask[i]; this->Tempsub[i]=subnetPlusMask[i]; } if( !isdigit(temp[0]) ) maskIsValid = false; else if( i == smLen-3 ){ temp[0]=subnetPlusMask[i+1]; } } //调用判别函数,并输出结果 ipTest::print(){ bool subIsV=subnetIsValid(Tempsub); bool ipIsV=ipIsValid(TempIp); if(!subIsV) cout<<\else cout<<\ \if(!maskIsValid) else cout<<\ else maskIsValid=false; } mask = atoi(temp); if( mask<0 || mask > 32) maskIsValid = false; temp[1]=subnetPlusMask[i+2]; if( !(isdigit(temp[0])&&isdigit(temp[1])) ) maskIsValid=false; strcpy( this->subnetPlusMask, subnetPlusMask); strcpy( this->ip, ip ); strcpy( this->TempIp, ip ); cout<<\ if(!ipIsV) cout<<\ else cout<<\ //判断IP是否belong subnet if(subIsV&&ipIsV&&maskIsValid) belong(); } //子函数,判断输入是否含有非数字字符 bool ipTest::NoIllegalChar(char *ch){ unsigned int i,k=0; for(i=0;i } } return true; } //判别IP地址是否合法 bool ipTest::ipIsValid(char * ip){ char ch[]=\ char *token,*dot[4]; int iplen=0; token=strtok(ip,ch); while(token!=NULL){ dot[iplen]=token; iplen++; token= strtok(NULL,ch); } //以\标志将IP字符串按节分开 //循环进行,知道结束 //将分开的每段赋值给dot } if(iplen!=4) {cout< return false;} //段数不对 for(int i=0;i<4;i++){ } return true; if(!NoIllegalChar(dot[i])||atoi(dot[i])>255) //有非法字符或某段值非法 return false; //判断子网号是否合法 bool ipTest::subnetIsValid(char* subnet){ } if( ! ipIsValid(subnet)) //调用判别IP地址合法性的函数 return false; return true; //判断IP是否为子网成员,判断子网号与掩码是否匹配,以及子网号、主机号全0全1问题 void ipTest::belong(){ int subLen=strlen(subnet); int ipLen=strlen(ip); unsigned int iIPA,iSubA,iMask; unsigned char subA[4],ipA[4]; char temp[3]; int i,j,t=0; for(i=0,j=0;i if(subnet[i] != '.') temp[j++]=subnet[i]; //temp数组中放'.'间的串 else{ subA[3-t] = atoi(temp); //subA数组中放'.'间的数据 j=0; t++; } } temp[0]=temp[1]=temp[2]='\\0'; subA[0] = atoi(temp); temp[0]=temp[1]=temp[2]='\\0'; iSubA = *( unsigned int *)subA; //iSubA中放subnet中'.'除外的串对应的数 for(i= 0, j= 0, t= 0; i ipA[0] = atoi(temp); iIPA = *( unsigned int* )ipA; //iIPA中放IP中'.'除外的串对应的数 iMask = 0xffffffff; if(ip[i] != '.') temp[j++] = ip[i]; else{ } ipA[3-t] = atoi(temp); j=0; t++; temp[0]=temp[1]=temp[2]='\\0'; iMask<<=(32-mask); //获取掩码 } if( ( iSubA ^ iMask ) == 0 ){ //说明子网号全1 } if( ( iSubA & iMask ) == 0 ){ //说明子网号全0 cout<<\子网号全0,error!\cout<<\子网号全1,error!\return; if( ( iSubA | iMask ) != iMask ){ //说明sub与mask不匹配 cout<<\子网号与掩码不匹配,error!\return;