Skip to content

Instantly share code, notes, and snippets.

@hpcx82
Created April 4, 2011 00:07
Show Gist options
  • Save hpcx82/900958 to your computer and use it in GitHub Desktop.
Save hpcx82/900958 to your computer and use it in GitHub Desktop.
(转)有一组从IP范围到地理位置信息的数据,不同地点的IP范围没有重叠,实现从单个IP地址查到相应的地理位置。
#include <iostream>
#include <algorithm>
#include <stdint.h>
#include <string>
#include <map>
#include <cassert>
using namespace std;
// ip range is expressed as [startIP, endIP)
// thus the MAX_IP is not available
struct Data
{
uint32_t startIP;
string geoLoc;
};
typedef map<uint32_t, Data> ipmap_t; // <endIP, Data>
bool getLocInIPRange(const ipmap_t& ipmap, uint32_t ip, string& loc)
{
ipmap_t::const_iterator it = ipmap.upper_bound(ip);
if(it != ipmap.end() && it->second.startIP <= ip)
{
loc = it->second.geoLoc;
return true;
}
return false;
}
void addMapItem(ipmap_t& ipmap, uint32_t startIP, uint32_t endIP, const char* loc)
{
Data data = {startIP, string(loc)};
pair<ipmap_t::iterator, bool> res = ipmap.insert(pair<uint32_t, Data>(endIP,data));
assert(res.second);
}
int main(int argc, const char* argv[])
{
ipmap_t ipmap;
addMapItem(ipmap, 0, 100, "Shanghai");
addMapItem(ipmap, 101, 303, "Xi'an");
addMapItem(ipmap, 406, 700, "Nanchang");
addMapItem(ipmap, 800, 900, "Nanjing");
addMapItem(ipmap, 1000, 1008, "Yuyao");
// search
while(true)
{
uint32_t ip;
cout << "please input ip: ";
cin >> ip;
string foundLoc;
bool exist = getLocInIPRange(ipmap, ip, foundLoc);
if(exist)
cout << foundLoc.c_str() << endl;
else
cout << "out of range!" << endl;
}
}
@hpcx82
Copy link
Author

hpcx82 commented Mar 28, 2012

原来如此:)
BTW, 你blog的文章挺有价值的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment