Skip to content

Instantly share code, notes, and snippets.

@baiyanhuang
Created April 4, 2011 00:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baiyanhuang/900958 to your computer and use it in GitHub Desktop.
Save baiyanhuang/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;
}
}
@rockeet
Copy link

rockeet commented Mar 26, 2012

作者未标明出处,这段代码的关键部分来自我的 blog:
http://blog.csdn.net/whinah/article/details/5791255

@baiyanhuang
Copy link
Author

看来我得加个转字:)

时间蛮长了,当时也是学习记录一下,要说出处,原始点还是陈硕的:
https://gist.github.com/900153

@rockeet
Copy link

rockeet commented Mar 28, 2012

呵呵,陈硕那个也是来源于我的另一篇blog:http://blog.csdn.net/whinah/article/details/6299288
当初他还给我发过信

@baiyanhuang
Copy link
Author

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

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