题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
#include <stdio.h> unsigned int AddressToInt(char str[])//地址转换成数字 { int ippart1,ippart2,ippart3,ippart4; ippart1=ippart2=ippart3=ippart4=-1; sscanf(str,"%d.%d.%d.%d",&ippart1,&ippart2,&ippart3,&ippart4); unsigned int b=(unsigned int)(ippart1<<24)+(unsigned int)(ippart2<<16)+(unsigned int)(ippart3<<8)+(unsigned int)ippart4; return b; } int IsIPAddress(char str[])//判断是否合法ip { int flag=0; int ippart1,ippart2,ippart3,ippart4; ippart1=ippart2=ippart3=ippart4=-1; flag=sscanf(str,"%d.%d.%d.%d",&ippart1,&ippart2,&ippart3,&ippart4); if(flag!=4) { flag=0; return flag; } if(ippart1<0||ippart1>255||ippart2<0||ippart2>255||ippart3<0||ippart3>255||ippart4<0||ippart4>255) { flag=0; return flag; } else { flag=1; return flag; } } int IsSubnetMask(char str[])//判断是否合法掩码 { int flag=0; if(IsIPAddress(str)) { int ippart1,ippart2,ippart3,ippart4; ippart1=ippart2=ippart3=ippart4=-1; sscanf(str,"%d.%d.%d.%d",&ippart1,&ippart2,&ippart3,&ippart4); unsigned int b=(unsigned int)(ippart1<<24)+(unsigned int)(ippart2<<16)+(unsigned int)(ippart3<<8)+(unsigned int)ippart4; b=~b+1; if((b&(b-1))==0) { flag=1; } } return flag; } int IsInSameSubnet(char str1[],char str2[],char str3[])//判断是否为同一子网 { int flag=0; if(IsSubnetMask(str1)&&IsIPAddress(str2)&&IsIPAddress(str3)) { unsigned int b1=AddressToInt(str1); unsigned int b2=AddressToInt(str2); unsigned int b3=AddressToInt(str3); if((b1&b2)==(b1&b3)) { flag=1; } } return flag; } int main() { char subnetMask[20]={0}; char ipAddress1[20]={0}; char ipAddress2[20]={0}; scanf("%s",subnetMask); // getchar(); scanf("%s",ipAddress1); // getchar(); scanf("%s",ipAddress2); // getchar(); int flag=-1; if((IsSubnetMask(subnetMask)==0)||(IsIPAddress(ipAddress1)==0)||(IsIPAddress(ipAddress2)==0)) { flag=1; } else if(IsInSameSubnet(subnetMask,ipAddress1,ipAddress2)) { flag=0; } else { flag=2; } printf("%d",flag); return 0; }