#include "OJ.h" #include <string> #include <iostream>using namespace std;/* function: To determine the IP address of two computers is the same subnet. Prototype: int issamesubnetwork (char * pcIp1, char * pcIp2, char * pcsubnetworkmask); input parameter: char * pcIP1: Computer 1 IP address, format: "192. 168.0.254 "; char * pcIP2: IP address of Computer 2, format:" 192.168.0.1 "; char * pcsubnetworkmask: Subnet mask, Format:" 255.255.255.0 "; return value: 0:ip1 IP2 is not the same subnet; 1:ip1 and IP2 belong to the same subnet; */void strtoints (char *ipadd, int* Iarr)//Convert IP address to integer, store in Iarr {char temp[4];memset ( Temp,0,sizeof (temp)); char *p = ipadd;int i =0;int j= 0;while (*p! = ') '//Put the first three in '. ' The split string is converted to an integer {if (*p! = '). {Temp [j] = *p;j++;++p;} Else{iarr[i] = atoi (temp); memset (temp,0,sizeof (temp)); j = 0;i++;++p;}} Iarr[i] = atoi (temp);//Convert the last string to an integer}int issamesubnetwork (char * pcIp1, char * pcIp2, char * pcsubnetworkmask) {/* is implemented here function */int Ip1[4]={0};int ip2[4] = {0};int mask[4] ={0};strtoints (PCIP1, IP1); Strtoints (PCIP2, IP2); Strtoints ( Pcsubnetworkmask, mask); for (int i =0; i < 4; ++i) {if (ip1[i]&mask[i])! = (Ip2[i] &mask[i))//Subnet number if there is a difference, then two IP addresses are not on the same subnet {return false;}} return true;} int main () {cout<<issamesubnetwork ("192.168.0.1", "192.168.0.254", "255.255.255.0") <<endl;return 0;}
Determine if the IP addresses of any two computers belong to the same subnet