华为OJ:判断两个IP是否属于同一子网

本文介绍了一种通过比较IP地址与子网掩码的位运算来判断IP地址是否位于同一子网内的方法。使用C++实现,包括IP地址合法性验证及字符串到数字的转换。

小菜鸟一枚,要是各位大神有简单的方法或者文中有错误的地方,欢迎交流。

问题描述:华为OJ:判断IP是否在一个子网内

判断方式是比较IP和mask位与的值是否相等。


#include<stdio.h>

#include<iostream>
#include<vector>
#include<string>

using namespace std;

vector<int> split(string str);
bool Isip(vector<int>);

int main()

{
string mask;
string add1;
string add2;
vector<int> intmask;
vector<int> intadd1;
vector<int> intadd2;
vector<int> result1;
vector<int> result2;
//字符串输入
getline(cin, mask);
getline(cin, add1);
getline(cin, add2);
intmask = split(mask);
intadd1 = split(add1);
intadd2 = split(add2);
if (Isip(intmask) == false || Isip(intadd1) == false || Isip(intadd1) == false)
cout << "1" << endl;
else
{
for (int i = 0; i < 4; i++)
{
int and1 = intmask[i] & intadd1[i];
result1.push_back(and1);
int and2 = intmask[i] & intadd2[i];
result2.push_back(and2);
}
if (result1 == result2)
cout << "0" << endl;
else
cout << "2" << endl;
}
return 0;
}
//函数:字符串分割并转数字
vector<int> split(string str)
{
vector<int> toInt;
vector<string> str2;
string::size_type pos = 0;
while ((pos = str.find_first_of('.', pos)) != string::npos)
{

string str1 = str.substr(0, pos);
str2.push_back(str1);
str = str.substr(pos + 1, str.size() - 1);
pos = 0;
}
str2.push_back(str);
for (vector<string>::iterator it = str2.begin(); it != str2.end(); it++)
{
int StringtoInt = atoi((*it).c_str());
toInt.push_back(StringtoInt);
}
return toInt;
}
//函数:判定ip是否合格
bool Isip(vector<int> ip)
{
vector<int>::iterator it;
for (it = ip.begin(); it != ip.end(); it++)
{
if (*it > 255)
return false;
if (it == ip.end() - 1)
{
return true;
}
}

}

1、字符串分割

     在字符串中循环查找‘.’出现的所有位置,返回该位置下标find_first_of(char c,pos)从pos位置查找

该字符串第一次出现的位置返回该字符的下标,否则返回npos:

     while ((pos = str.find_first_of('.', pos)) != string::npos)

     找到该位置下标后利用提取字符串中子字符串方法提取该下标到初始位置的字符串并压入vector中:

     string str1 = str.substr(0, pos);

     同时将该下标+1(‘.’之后)的字符串作为新的字符串进行查找

     str = str.substr(pos + 1, str.size() - 1);

     清pos值;

     至此,已将‘.’之前所有的字符串压入vector;

     ‘.’之后的值就为最后更新过的新的字符串。

2、vector<string>转vector<int>

    字符串转数字函数int atoi(const char* str)将char*转为int整数,

    int StringtoInt = atoi((*it).c_str());

    c_str()函数原型为const char* c_str();目的是将string对象转为char*型。

3、按位与&

     int and1 = intmask[i] & intadd1[i];

     将转为数字的ip的每一位位与mask得到位与的十进制数。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值