标签:blog io ar os sp for 2014 log ad
#include "OJ.h" #include<string> #include<iostream> using namespace std; /* 功能: 判断两台计算机IP地址是同一子网络。 原型: int IsSameSubNetwork(char * pcIp1, char * pcIp2, char * pcSubNetworkMask); 输入参数: char * pcIP1: 计算机1的IP地址,格式:“192.168.0.254”; char * pcIP2: 计算机2的IP地址,格式:“192.168.0.1”; char * pcSubNetworkMask: 子网掩码,格式:“255.255.255.0”; 返回值: 0:IP1与IP2不属于同一子网络; 1:IP1与IP2属于同一子网络; */ void strToInts(char *ipAdd, int* iArr )//将ip地址转换成整型,存储到iArr中 { char temp[4]; memset(temp,0,sizeof(temp)); char *p = ipAdd; int i =0; int j= 0; while (*p != '\0')//将前三个用'.'分割的字符串转换成整数 { 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);//将最后一段字符串转换成整数 } int IsSameSubNetwork(char * pcIp1, char * pcIp2, char * pcSubNetworkMask) { /*在这里实现功能*/ 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]))//子网号码如果有不同的,则两个Ip地址不在同一子网 { return false; } } return true; } int main() { cout<<IsSameSubNetwork("192.168.0.1", "192.168.0.254", "255.255.255.0")<<endl; return 0; }
标签:blog io ar os sp for 2014 log ad
原文地址:http://blog.csdn.net/xiaohanstu/article/details/41907953