读取纯真IP数据库

来源:互联网 发布:java <div class=" 编辑:程序博客网 时间:2024/06/11 07:03
#define  _CRT_SECURE_NO_WARNINGS#include <iostream>#include <string>#include <stdlib.h>#include <windows.h>using namespace std;char *ptr = NULL;//ptr of image//内存映射文件char *p = NULL;//point to index//索引区unsigned int total;//ip countinline void Load(void){HANDLEhnd;//file handleDWORDNumberOfBytesRead;//lenchartext[2048];//patchchar*temp;unsigned int len;//get patchif( !GetModuleFileName(0, text, 2048))return;temp = strrchr(text, 92);// 92 = '\'*(temp + 1) = NULL;strcat(temp, "QQwry.dat");//CreateFilehnd = CreateFile(text, GENERIC_READ, FILE_SHARE_READ, NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);if(INVALID_HANDLE_VALUE == hnd){::MessageBox(NULL, text, "不能打开文件!", NULL);return;}//get lenlen = SetFilePointer(hnd, NULL, NULL, FILE_END);SetFilePointer(hnd, NULL, NULL, FILE_BEGIN);//mallocptr = (char*)malloc(len + 9);if(!ptr){CloseHandle(hnd);::MessageBox(NULL, "不能分配内存!", NULL, NULL);return;}//readif(!ReadFile(hnd, ptr, len, &NumberOfBytesRead, NULL)){CloseHandle(hnd);free(ptr);::MessageBox(NULL, text, "不能读入文件!", NULL);return;}CloseHandle(hnd);//calc total - 1total = (*((unsigned int*)ptr + 1) - *(unsigned int*)ptr);//check fileif(total % 7 != 0){free(ptr);::MessageBox(NULL, text, "QQwry.dat文件有损坏!", NULL);return;}total /= 7;++total;p = ptr + *(unsigned int*)ptr;  //ptr of index area}inline unsigned int get_3b(const char *mem){return 0x00ffffff & *(unsigned int*)(mem);}inline unsigned int str2ip(const char *lp){unsigned int iIP = 0;unsigned int tmpIP = 0;while(*lp){if('.' == *lp){iIP = 256 * iIP + tmpIP;tmpIP = 0;}else{tmpIP = 10 * tmpIP + *lp - '0';}++lp;}iIP = 256 * iIP + tmpIP;return iIP;}string _GetAddress(string IPstr){string ret;if(NULL == p){ret = "";return ret;}unsigned int ip = str2ip(IPstr.c_str());char *now_p;unsigned int begin = 0, end = total;while(true){if( begin >= end - 1 ){break;}if( ip < *(unsigned int*)(p + (begin + end)/2 * 7)){end = (begin + end) / 2;}else{begin = (begin + end) / 2;}}unsigned int temp = get_3b(p + 7 * begin + 4);if(ip <= *(unsigned int*)(ptr + temp))//ok, found{now_p = ptr + temp + 4;if( 0x01 == *now_p )//如果0x01跳过去找国家{now_p = ptr + get_3b(now_p + 1);}//countryif( 0x02 == *now_p )//如果国家0x02再跳{ret = ptr + get_3b(now_p + 1);now_p += 4;}else{ret = now_p;for(; *now_p; ++now_p);++now_p;}//localif( 0x02 == *now_p ) //找到国家以后还发现0x02跳过去找地区{ret += ptr + get_3b(now_p + 1);}else{ret += now_p;}}else{ret = "未知数据";}return ret;}int main(void){Load();string ip;while (cin >> ip){cout << _GetAddress(ip) << endl;}return 0;}



http://hzy3774.iteye.com/blog/1851364

http://hzy3774.iteye.com/blog/1851364