题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
#include <stdio.h> #include <string.h> int isip(int ip[])//判定是否是合法IP,以及IP分类 { int flag=-1; if((ip[0]==0)||(ip[0]==127)) { flag=-2; } else if((ip[0]>=1)&&(ip[1]>=0)&&(ip[2]>=0)&&(ip[3]>=0)&&(ip[0]<=255)&&(ip[1]<=255)&&(ip[2]<=255)&&(ip[3]<=255)) { if(ip[0]>=1&&ip[0]<=126) { flag=1; } else if(ip[0]>=128&&ip[0]<=191) { flag=2; } else if(ip[0]>=192&&ip[0]<=223) { flag=3; } else if(ip[0]>=224&&ip[0]<=239) { flag=4; } else if(ip[0]>=240&&ip[0]<=255) { flag=5; } } else { flag=0; } return flag; } int isdns(int dns[])//判断是否为合法子网掩码 { int flag=-1; if((isip(dns))<=0) { flag=0; } unsigned int a=0; unsigned int b=0; a=(dns[0]<<24)+(dns[1]<<16)+(dns[2]<<8)+dns[3]; b=(~a)+1; if((b&(b-1))==0) { flag=1; } else { flag=0; } if(a==0||((dns[0]==255)&&(dns[1]==255)&&(dns[2]=255)&&(dns[3]==255))) { flag=0; } return flag; } int ispri(int ip[])//判断是否为私有ip { int flag=-1; if((isip(ip))>=1) { if((ip[0]==10)||((ip[0]==172)&&((ip[1]>=16)&&(ip[1]<=31))||((ip[0]==192)&&(ip[1]==168)))) { flag=1; } } return flag; } int main() { int fa=0,fb=0,fc=0,fd=0,fe=0,ferr=0,fpri=0; int ip[4]={0}; int dns[4]={0}; char str[200]={0}; while(scanf("%s",str)!=EOF) { memset(ip,-1,4*sizeof(int)); memset(dns,-1,4*sizeof(int)); sscanf(str,"%d.%d.%d.%d~%d.%d.%d.%d",&ip[0],&ip[1],&ip[2],&ip[3],&dns[0],&dns[1],&dns[2],&dns[3]); if((ip[0]==0)||(ip[0]==127))//判断是否为不计数ip { continue; } if(isdns(dns)<=0)//掩码合法否 { ferr++; continue; } else if(isip(ip)<=0)//ip合法否 { ferr++; continue; } else//ip分类 { switch(isip(ip)) { case 1: fa++; break; case 2:fb++;break; case 3:fc++;break; case 4:fd++;break; case 5:fe++;break; } if(ispri(ip)>=1) { fpri++; } } } printf("%d %d %d %d %d %d %d",fa,fb,fc,fd,fe,ferr,fpri);//输出结果 }