Created
April 4, 2011 00:07
-
-
Save hpcx82/900958 to your computer and use it in GitHub Desktop.
(转)有一组从IP范围到地理位置信息的数据,不同地点的IP范围没有重叠,实现从单个IP地址查到相应的地理位置。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
} |
呵呵,陈硕那个也是来源于我的另一篇blog:http://blog.csdn.net/whinah/article/details/6299288
当初他还给我发过信
原来如此:)
BTW, 你blog的文章挺有价值的。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
看来我得加个转字:)
时间蛮长了,当时也是学习记录一下,要说出处,原始点还是陈硕的:
https://gist.github.com/900153