在我们的组织,我们收到每日黑名单(更大,因为这仅仅是一个片断)的格式如下:意外的结果
172.44.12.0
198.168.1.5
10.10。 0.0
192.168.78.6
192.168.22.22
111.111.0.0
222.222.0.0
12.12.12.12
当运行该程序的代码编译后我得到:
我使用C++在Linux/Unix环境。
到目前为止,我只是吐出来确保我的格式正确。
该文件的名称是blacklist.txt,其中包含目前上面列出的IP。我只使用cout来确保我的变量被正确定义。
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <netinet/in.h>
#include <stdint.h>
#include <arpa/inet.h>
using namespace std;
bool is_match(std::string &hay_stack, std::string &srcip) {
in_addr_t _ip = inet_addr(hay_stack.c_str());
in_addr_t _IP = inet_addr(srcip.c_str());
_ip = ntohl(_ip);
_IP = ntohl(_IP);
uint32_t mask=(_ip & 0x00ffffff == 0) ? 0xff000000 :
(_ip & 0x0000ffff == 0 ? 0xffff0000 : 0);
return ((_ip & mask) == (_IP & mask));
}
int main()
{
vector<std::string> lines;
lines.reserve(5000); //Assuming that the file to read can have max 5K lines
string fileName("blacklist.txt");
ifstream file;
file.open(fileName.c_str());
if(!file.is_open())
{
cerr<<"Error opening file : "<<fileName.c_str()<<endl;
return -1;
}
//Read the lines and store it in the vector
string line;
while(getline(file,line))
{
lines.push_back(line);
}
file.close();
//Dump all the lines in output
for(unsigned int i = 0; i < lines.size(); i++)
{
string h = lines[i];
string mi = "10.10.10.10";
cout<<is_match(h,mi)<<endl;
}
return 0;
}
我期待的输出为10.10.10.10(某种这里主机的子网)10.10.0.0(和某种这里子网掩码)
我猜“面具”始终评估为零。 – 2012-03-02 20:23:53
您有特定的问题吗?或者我们应该为您解决这个问题? – PlasmaHH 2012-03-02 20:24:12
即使你没有提供任何问题,我还是会为+1做准备:提供一个完整的程序(http://sscce.org),并使用正确的方式读取输入的行。 – 2012-03-02 20:28:52