C语言中判断两个IPv4地址是否属于同一个子网的代码

2020-01-06 17:44:17于海丽

转化为十进制后为:
     192.168.0.0
通过以上对两台计算机IP地址与子网掩码的AND运算后,我们可以看到它运算结果是一样的。均为192.168.0.0,所以这二台计算机可视为是同一子网络。
/*
* 功能: 判断两台计算机IP地址是同一子网络。
* 输入参数: String Mask: 子网掩码,格式:“255.255.255.0”;
* String ip1: 计算机1的IP地址,格式:“192.168.0.254”;
* String ip2: 计算机2的IP地址,格式:“192.168.0.1”;
*
* 返回值: 0:IP1与IP2属于同一子网络; 1:IP地址或子网掩码格式非法; 2:IP1与IP2不属于同一子网络
*/
public int checkNetSegment(String mask, String ip1, String ip2)
{
/*在这里实现功能*/
return 0;
}
输入描述:

输入子网掩码、两个ip地址
输出描述:

得到计算结果
输入例子:

255.255.255.0
192.168.224.256
192.168.10.4

输出例子:

1
解答代码:


#include<iostream>
#include<fstream>
#include<string>
#include<cstring>
#include<cctype>
#include<algorithm>
#include<cstdlib>
using namespace std;

typedef struct ip
{
 int first;
 int second;
 int three;
} IP;

int judgeIp(string ipSubNet,IP &ip)
{
 int index=0;
 ip.first=atoi(&ipSubNet[index]);
 if(ip.first>255)
 return 0;

 index++;
 index=ipSubNet.find_first_of('.',index);
 ip.second=atoi(&ipSubNet[++index]);
 if(ip.second>255)
 return 0;

 index++;
 index=ipSubNet.find_first_of('.',index);
 ip.three=atoi(&ipSubNet[++index]);
 if(ip.three>255)
 return 0;

 index++;
 index=ipSubNet.find_first_of('.',index);
 ip.fouth=atoi(&ipSubNet[++index]);
 if(ip.fouth>255)
 return 0;

 return 1;
}

int main()
{
 string ipSubNet,ipAdd1,ipAdd2;
 IP subNet,ip1,ip2;
 while(cin>>ipSubNet>>ipAdd1>>ipAdd2)
 {
 if(judgeIp(ipSubNet,subNet)&&judgeIp(ipAdd1,ip1)&&judgeIp(ipAdd2,ip2))
 {
  ip1.first=ip1.first & subNet.first;
  ip1.second=ip1.first & subNet.second;
  ip1.second=ip1.first & subNet.second;
  ip1.fouth=ip1.first & subNet.fouth;

  ip2.first=ip2.first & subNet.first;
  ip2.second=ip2.first & subNet.second;
  ip2.second=ip2.first & subNet.second;
  ip2.fouth=ip2.first & subNet.fouth;

  if(ip1.first==ip2.first&&ip1.second==ip2.second&&ip1.three==ip2.three&&ip1.fouth==ip2.fouth)
  cout<<'0'<<endl;
  else
  cout<<'2'<<endl;
 }
 else
  cout<<'1'<<endl;
 }
 return 0;
}

C语言——如何判断两个IP在同一网段


ip_addr.h

#define ip_addr_netcmp(addr1, addr2, mask) (((addr1)->addr & 
                       (mask)->addr) == 
                       ((addr2)->addr & 
                       (mask)->addr))