archive the v1.0 - old db structure

This commit is contained in:
lion 2022-06-16 16:25:31 +08:00
parent bfd70f95dd
commit 1e2544cc57
150 changed files with 0 additions and 706936 deletions

View File

@ -1,61 +0,0 @@
### 1.8
1. 数据升级至2018/12/31的版本国外的也增加了大量的城市数据。
2. Java的binding的Searcher类增加了如下的接口和实现
```java
DbSearcher(DbConfig dbConfig, string dbBinStr);
```
maven坐标
```xml
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7.2</version>
</dependency>
```
3. Javascript的pacakge上传到了npm。
4. 增加纯lua实现的lua binding (lua 5.2版本依赖bit模块对5.3的支持将使用lua自带的bit操作)。
5. 增加C实现的lua_c binding (和c的性能等同建议使用)。
6. 优化部分binding的demo运行和使用文档。
7. 修复python binding的benchmark的部分错误。
### 1.2.4
1, 花了近两周的时间重写了数据的升级算法,再次提高准确率,升级过程如下(此处应该有掌声):
```shell
1. ip预分段利于分布式同步升级
2. 分段同步升级,目前使用四个机器同时升级
3自动验证数据查缺补全
4数据合并
5数据格式标准化目前2个工作
1)ipip.net的数据和淘宝数据保持区域名称统一ipip.net的数据不带“省”和“市”关键字。
2)香港澳门台湾等国家信息修复淘宝原始数据有问题reported at http://git.oschina.net/lionsoul/ip2region/issues/21
6重复ip段的合并得到data目录下的ip.merge.txt
7生产data目录下的ip2region.db二进制数据库文件
```
2修复原始数据关于“香港台湾澳门”国家信息错误的bugreported at http://git.oschina.net/lionsoul/ip2region/issues/21
3将数据升级至2017/03/15同步版本
4增加c_mmap查询客户端C客户端查询文件读取使用内存映射加速感谢[Leo Ma](http://git.oschina.net/begeekmyfriend)的贡献
备注部分阿里云数据有问题缺失的部分使用免费开放的ipip.net的数据代替了。
### 1.2.3
1. 优化升级算法进行更深度的分裂可以使准确率再度提高同时数据的更新也花费了2天多的时间
2. 数据升级至2016/12/14版本的数据包括原始数据和binary数据库的数据
### 1.2.2
1. ip数据文件更新至2016/11/02版本
2. 增加ip2region.db数据库文件的java生成工具请参考README获取使用方式
3. 新增golang查询客户端的实现感谢 [@mohong122](https://github.com/mohong122) 的关注和贡献
### 1.2
1. 新增分列式升级算法大大的增加了数据的准确率基本避免之前各大网友反馈的些许ip定位错误
2. 数据升级是2016/06/30版
3. 优化数据文件生成算法ip2region.db文件由原来的3.5M降为1.5M42亿个IP地址皆大欢喜啊
4. C/PHP/JAVA客户端增加纯内存搜索模式python, php扩展nodejs会在后续版本加上
说明因为数据文件只有1.5M对于PHP,java这类IO优化类语言提升速度不大C有一个数量级的提升

View File

@ -1,2 +0,0 @@
[workspace]
members = ["binding/rust", "binding/rust/example"]

175
README.md
View File

@ -1,175 +0,0 @@
# Ip2region是什么
阅读其他语言介绍:[简体中文](README.md) | [English](README_en.md)
ip2region - 准确率99.9%的离线IP地址定位库0.0x毫秒级查询ip2region.db数据库只有数MB提供了java,php,c,python,nodejs,golang,c#等查询绑定和Binary,B树,内存三种查询算法。
# Ip2region特性
### 99.9%准确率
数据聚合了一些知名ip到地名查询提供商的数据这些是他们官方的的准确率经测试着实比经典的纯真IP定位准确一些。<br />
ip2region的数据聚合自以下服务商的开放API或者数据(升级程序每秒请求次数2到4次): <br />
01, &gt;80%, 淘宝IP地址库, [http://ip.taobao.com/](http://ip.taobao.com/) <br />
02, ≈10%, GeoIP, [https://geoip.com/](https://geoip.com/) <br />
03, ≈2%, 纯真IP库, [http://www.cz88.net/](http://www.cz88.net/) <br />
<b>备注:</b>如果上述开放API或者数据都不给开放数据时ip2region将停止数据的更新服务。
### 标准化的数据格式
每条ip数据段都固定了格式
```
_城市Id|国家|区域|省份|城市|ISP_
```
只有中国的数据精确到了城市其他国家有部分数据只能定位到国家后前的选项全部是0已经包含了全部你能查到的大大小小的国家请忽略前面的城市Id个人项目需求
### 体积小
包含了全部的IP生成的数据库文件ip2region.db只有几MB最小的版本只有1.5MB随着数据的详细度增加数据库的大小也慢慢增大目前还没超过8MB。
### 查询速度快
全部的查询客户端单次查询都在0.x毫秒级别内置了三种查询算法
1. memory算法整个数据库全部载入内存单次查询都在0.1x毫秒内C语言的客户端单次查询在0.00x毫秒级别。
2. binary算法基于二分查找基于ip2region.db文件不需要载入内存单次查询在0.x毫秒级别。
3. b-tree算法基于btree算法基于ip2region.db文件不需要载入内存单词查询在0.x毫秒级别比binary算法更快。
任何客户端b-tree都比binary算法快当然memory算法固然是最快的
### 多查询客户端的支持
已经集成的客户端有java、C#、php、c、python、nodejs、php扩展(php5和php7)、golang、rust、lua、lua_c, nginx。
binding | 描述 | 开发状态 | binary查询耗时 | b-tree查询耗时 | memory查询耗时
:-: | :-: | :-: | :-: | :-: | :-:
[c](binding/c) | ANSC c binding | 已完成 | 0.0x毫秒 | 0.0x毫秒 | 0.00x毫秒
[c#](binding/c#) | c# binding | 已完成 | 0.x毫秒 | 0.x毫秒 | 0.1x毫秒
[golang](binding/golang) | golang binding | 已完成 | 0.x毫秒 | 0.x毫秒 | 0.1x毫秒
[java](binding/java) | java binding | 已完成 | 0.x毫秒 | 0.x毫秒 | 0.1x毫秒
[lua](binding/lua) | lua实现的binding | 已完成 | 0.x毫秒 | 0.x毫秒 | 0.x毫秒
[lua_c](binding/lua_c) | lua的c扩展 | 已完成 | 0.0x毫秒 | 0.0x毫秒 | 0.00x毫秒
[nginx](binding/nginx) | nginx的c扩展 | 已完成 | 0.0x毫秒 | 0.0x毫秒 | 0.00x毫秒
[nodejs](binding/nodejs) | nodejs | 已完成 | 0.x毫秒 | 0.x毫秒 | 0.1x毫秒
[php](binding/php) | php实现的binding | 已完成 | 0.x毫秒 | 0.1x毫秒 | 0.1x毫秒
[php5_ext](binding/php5_ext) | php5的c扩展 | 已完成 | 0.0x毫秒 | 0.0x毫秒 | 0.00x毫秒
[php7_ext](binding/php7_ext) | php7的c扩展 | 已完成 | 0.0毫秒 | 0.0x毫秒 | 0.00x毫秒
[python](binding/python) | python bindng | 已完成 | 0.x毫秒 | 0.x毫秒 | 0.x毫秒
[rust](binding/rust) | rust binding | 已完成 | 0.x毫秒 | 0.x毫秒 | 0.x毫秒
# ip2region快速测试
请参考每个binding下的README说明去运行cli测试程序例如C语言的demo运行如下
```shell
cd binding/c/
gcc -g -O2 testSearcher.c ip2region.c
./a.out ../../data/ip2region.db
```
会看到如下cli界面
```shell
initializing B-tree ...
+----------------------------------+
| ip2region test script |
| Author: chenxin619315@gmail.com |
| Type 'quit' to exit program |
+----------------------------------+
p2region>> 101.105.35.57
2163|中国|华南|广东省|深圳市|鹏博士 in 0.02295 millseconds
```
输入IP地址开始测试第一次会稍微有点慢在运行命令后面接入binary,memory来尝试其他算法建议使用b-tree算法速度和并发需求的可以使用memory算法具体集成请参考不同binding下的测试源码。
# ip2region安装
具体请参考每个binding下的README文档和测试demo以下是一些可用的快捷安装方式
### maven仓库地址
```xml
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7.2</version>
</dependency>
```
### nodejs
```
npm install node-ip2region --save
```
### nuget安装
```shell
Install-Package IP2Region
```
### php composer
```shell
# 插件来自https://github.com/zoujingli/ip2region
composer require zoujingli/ip2region
```
# ip2region 并发使用
1. 全部binding的各个search接口都<b>不是</b>线程安全的实现不同线程可以通过创建不同的查询对象来使用并发量很大的情况下binary和b-tree算法可能会打开文件数过多的错误请修改内核的最大允许打开文件数(fs.file-max=一个更高的值)或者使用持久化的memory算法。
2. memorySearch接口在发布对象前进行一次预查询(本质上是把ip2region.db文件加载到内存),可以安全用于多线程环境。
# ip2region.db的生成
从1.8版本开始ip2region开源了ip2region.db生成程序的java实现提供了ant编译支持编译后会得到以下提到的dbMaker-{version}.jar对于需要研究生成程序的或者更改自定义生成配置的请参考${ip2region_root}/maker/java内的java源码。
从ip2region 1.2.2版本开始里面提交了一个dbMaker-{version}.jar的可以执行jar文件用它来完成这个工作
1. 确保你安装好了java环境不玩Java的童鞋就自己谷歌找找拉临时用一用几分钟的事情
2. cd到${ip2region_root}/maker/java然后运行如下命令
```shell
java -jar dbMaker-{version}.jar -src 文本数据文件 -region 地域csv文件 [-dst 生成的ip2region.db文件的目录]
# 文本数据文件db文件的原始文本数据文件路径自带的ip2region.db文件就是/data/ip.merge.txt生成而来的你可以换成自己的或者更改/data/ip.merge.txt重新生成
# 地域csv文件该文件目的是方便配置ip2region进行数据关系的存储得到的数据包含一个city_id这个直接使用/data/origin/global_region.csv文件即可
# ip2region.db文件的目录是可选参数没有指定的话会在当前目录生成一份./data/ip2region.db文件
```
3. 获取生成的ip2region.db文件覆盖原来的ip2region.db文件即可
4. 默认的ip2region.db文件生成命令:
```shell
cd ${ip2region_root}/java/
java -jar dbMaker-1.2.2.jar -src ./data/ip.merge.txt -region ./data/global_region.csv
# 会看到一大片的输出
```
# 相关备注
### 声明
ip2region重点在于<b>研究IP数据的存储设计和各种语言的查询实现</b>并没有原始IP数据的支撑数据来源请参考上面的描述升级数据需要很多IP的支撑并且会对原始平台造成一定量的请求压力本项目不保证及时的数据更新没有也不会有商用版本你可以使用自定义的数据导入ip2region进行自定义查询的实现。
### 技术交流
1. 数据库文件的结构和原理请阅读 @冬芽 的blog[“ip2region数据库文件的结构和原理”](https://github.com/dongyado/dongyado.github.io/blob/master/_posts/2016-08-18-structure-of-ip2region-database-file.md)[ip2region数据结构设计和实现视频分享](https://www.bilibili.com/video/BV1wv4y1N7SD)
2. ip2region交流分享微信lionsoul2014(请备注ip2region)QQ1187582057(很少关注)
3. 基于检测算法的数据更新方式视频分享:[数据更新实现视频分享part1](https://www.bilibili.com/video/BV1934y1E7Q5/)[数据更新实现视频分享part2](https://www.bilibili.com/video/BV1pF411j7Aw/)

View File

@ -1,197 +0,0 @@
# What is Ip2region?
Read this in other languages: [简体中文](README.md) | [English](README_en.md)
ip2region - offline IP address location library with 99.9% accuracy, 0.0x millisecond queries, ip2region.db database is only a few MB, provides query bindings for
```
java|php|c|python|nodejs|golang|c#
```
and three query algorithms for
```
Binary|B-tree|memory
```
# Ip2region features
### 99.9% accuracy rate
The data is aggregated from some well-known ip to place name lookup providers, these are their official accuracy rates, tested to be actually a bit more accurate than the classic pure IP location.
The data of ip2region is aggregated from the open API or data of the following service providers (2 to 4 requests per second for the upgrade program):
01. &gt;80% - [Taobao IP address database](http://ip.taobao.com/) <br />
02. ≈10% - [GeoIP](https://geoip.com/) <br />
03. ≈2% - [Pure IP Library](http://www.cz88.net/) <br />
<b>Remarks:</b> If none of the above open APIs or data give open data ip2region will stop the update service for the data.
### Standardized data format
Each ip data segment has a fixed format of.
```
_cityId|country|region|province|city|ISP_
```
Only the data for China is accurate to the city, some of the data for other countries can only be located to the country, and all the options before the latter are 0, which already contains all the big and small countries you can check (please ignore the city Id in front, personal project requirements).
### Small size
Contains all the IPs, the generated database file ip2region.db is only a few MB, the smallest version is only 1.5 MB, with the increase in the level of detail of the data the size of the database is slowly increasing, currently not more than 8 MB.
### Fast query speed
All of the query client single query are in the 0.x millisecond level, built-in three query algorithms
1. memory algorithm: the entire database is loaded into memory, single query are within 0.1x milliseconds, C language client single query in 0.00x milliseconds level.
2. binary algorithm: based on dichotomous lookup, based on ip2region.db file, no need to load memory, single query in 0.x milliseconds level.
3. b-tree algorithm: based on btree algorithm, based on ip2region.db file, no need to load memory, word query at 0.x milliseconds level, faster than binary algorithm.
Any client b-tree is faster than binary algorithm, of course memory algorithm is certainly the fastest!
### Multi-query client support
Clients already integrated are:
```
java, C#, php, c, python, nodejs, php extensions (php5 and php7), golang, rust, lua, lua_c, nginx.
```
binding | description | development status | binary query time consuming | b-tree query time consuming | memory query time consuming
:-: | :-: | :-: | :-: | :-: | :-:
[c](binding/c) | ANSC c binding | completed | 0.0x ms | 0.0x ms | 0.00x ms
[c#](binding/c#) | c# binding | completed | 0.x ms | 0.x ms | 0.1x ms
[golang](binding/golang) | golang binding | done | 0.x ms | 0.x ms | 0.1x ms
[java](binding/java) | java binding | completed | 0.x ms | 0.x ms | 0.1x ms
[lua](binding/lua) | lua implementation of binding | done | 0.x ms | 0.x ms | 0.x ms
[lua_c](binding/lua_c) | lua's c extension | done | 0.0x ms | 0.0x ms | 0.00x ms
[nginx](binding/nginx) | c extensions for nginx | done | 0.0x ms | 0.0x ms | 0.00x ms
[nodejs](binding/nodejs) | nodejs | completed | 0.x ms | 0.x ms | 0.1x ms
[php](binding/php) | php implementation of binding | done | 0.x ms | 0.1x ms | 0.1x ms
[php5_ext](binding/php5_ext) | c extensions for php5 | done | 0.0x ms | 0.0x ms | 0.00x ms
[php7_ext](binding/php7_ext) | c extensions for php7 | done | 0.0x ms | 0.0x ms | 0.00x ms
[python](binding/python) | python bindng | done | 0.x ms | 0.x ms | 0.x ms
[rust](binding/rust) | rust binding | done | 0.x ms | 0.x ms | 0.x ms
# ip2region quick test
Please refer to the README instructions under each binding to run the cli test program, for example the C demo runs as follows.
```shell
cd binding/c/
gcc -g -O2 testSearcher.c ip2region.c
. /a.out ... /... /data/ip2region.db
```
You will see the following cli interface.
```
initializing B-tree ...
+----------------------------------+
| ip2region test script |
| Author: chenxin619315@gmail.com |
| Type 'quit' to exit program |
+----------------------------------+
p2region>> 101.105.35.57
2163|China|South|Guangdong|Shenzhen|Dr. Peng in 0.02295 millseconds
```
Enter the IP address to start the test, the first time will be slightly slow, after the run command access binary,memory to try other algorithms, it is recommended to use the b-tree algorithm, speed and concurrency requirements can use the memory algorithm, please refer to the test source code under different binding for specific integration.
# ip2region installation
Refer to the README documentation and test demos under each binding for details, and here are some available shortcut installations.
### maven repository address
```xml
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7.2</version>
</dependency>
```
### nodejs
```
npm install node-ip2region --save
```
### nuget install
```shell
NuGet install IP2Region
```
### php composer
```shell
# Plugin from: https://github.com/zoujingli/ip2region
composer require zoujingli/ip2region
```
# ip2region Concurrent use
1. each search interface of all binding is <b>not</b> a thread-safe implementation, different threads can use it by creating different query objects. with high concurrency, the binary and b-tree algorithms may have too many open files error, please modify the kernel's maximum number of open files allowed (fs.file-max=a higher value), or use a persistent memory algorithm.
2. memorySearch interface, which performs a pre-query before publishing the object (essentially loading the ip2region.db file into memory), can be safely used in a multi-threaded environment.
# ip2region.db generation
Starting from version 1.8, ip2region has open sourced the java implementation of the ip2region.db generator, providing ant compilation support, which will result in the dbMaker-{version}.jar mentioned below, for those who need to study the generator or change the custom generation configuration please refer to ${ip2region_ root}/maker/java for the java source code.
Starting with ip2region version 1.2.2 there is an executable jar file dbMaker-{version}.jar committed inside, which is used to do this.
1. make sure you have the java environment installed (kids who don't play with Java will Google themselves to find a pull, temporary use, a matter of minutes)
2. cd to `${ip2region_root}/maker/java` and run the following command.
```shell
java -jar dbMaker-{version}.jar -src text data file -region geographic csv file [-dst directory of the generated ip2region.db file]
# text data file: the original text data file path of the db file, the self-contained ip2region.db file is generated from /data/ip.merge.txt, you can replace it with your own or change /data/ip.merge.txt to regenerate it
# geographic csv file: the purpose of this file is to facilitate the configuration of ip2region for data relationship storage, the data obtained contains a city_id, this can be directly used /data/origin/global_region.csv file
# ip2region.db file directory: is optional, if not specified, a copy will be generated in the current directory. /data/ip2region.db file
```
3. get the generated ip2region.db file to overwrite the original ip2region.db file
4. The default ip2region.db file generation command:
```shell
cd ${ip2region_root}/java/
java -jar dbMaker-1.2.2.jar -src . /data/ip.merge.txt -region . /data/global_region.csv
# You'll see a big chunk of output
```
# Related remarks
### Declaration
ip2region focuses on <b>
researching IP data storage design and query implementation in various languages</b>, there is no original IP data support, please refer to the description above for data sources, upgrading data requires a lot of IP support and will cause a certain amount of request pressure on the original platform, this project does not guarantee timely data updates, there is no and will not be a commercial version, you can use You can use the custom data import ip2region for custom query implementation.
### Technical Communication
1. the structure and principle of the database file, please read @冬芽's blog:
- [ip2region Database File Structure and Principle](https://github.com/dongyado/dongyado.github.io/blob/master/_posts/2016-08-18-structure-of-ip2region-database-file.md)
- [ip2region Data Structure Design and Implementation Video share](https://www.bilibili.com/video/BV1wv4y1N7SD)
2. ip2region exchange and sharing
- WeChat: lionsoul2014 (please note ip2region)
- QQ: 1187582057 (little attention)
3. based on the detection algorithm of the data update way video sharing:
- [Data Update to Achieve Video Sharing Part1](https://www.bilibili.com/video/BV1934y1E7Q5/)
- [Data Update to Achieve Video Sharing part2](https://www.bilibili.com/video/BV1pF411j7Aw/)

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,13 +0,0 @@
<?xml version='1.0' encoding='UTF-8'?>
<Library LVVersion="19008000">
<Property Name="NI.Lib.Icon" Type="Bin">'1#!!!!!!!)!"1!&amp;!!!-!%!!!@````]!!!!"!!%!!!(]!!!*Q(C=\&gt;7R=2MR%!81N=?"5Q&lt;/07RB7W!,&lt;'&amp;&lt;9+K1,7Q,&lt;)%N&lt;!NMA3X)DW?-RJ(JQ"I\%%Z,(@`BA#==ZB3RN;]28_,V7@PWW`:R`&gt;HV*SU_WE@\N_XF[3:^^TX\+2YP)D7K6;G-RV3P)R`ZS%=_]J'XP/5N&lt;XH,7V\SEJ?]Z#5P?=J4HP+5JTTFWS%0?=B$DD1G(R/.1==!IT.+D)`B':\B'2Z@9XC':XC':XBUC?%:HO%:HO&amp;R7QT0]!T0]!S0I4&lt;*&lt;)?=:XA-(]X40-X40-VDSGC?"GC4N9(&lt;)"D2,L;4ZGG?ZH%;T&gt;-]T&gt;-]T?.S.%`T.%`T.)^&lt;NF8J4@-YZ$S'C?)JHO)JHO)R&gt;"20]220]230[;*YCK=ASI2F=)1I.Z5/Z5PR&amp;)^@54T&amp;5TT&amp;5TQO&lt;5_INJ6Z;"[(H#&gt;ZEC&gt;ZEC&gt;Z$"(*ETT*ETT*9^B)HO2*HO2*(F.&amp;]C20]C2)GN4UE1:,.[:/+5A?0^NOS?UJ^3&lt;*\9B9GT@7JISVW7*NIFC&lt;)^:$D`5Q9TWE7)M@;V&amp;D,6;M29DVR]6#R],%GC47T9_/=@&gt;Z5V&gt;V57&gt;V5E&gt;V5(OV?^T[FTP?\`?YX7ZRP6\D=LH%_8S/U_E5R_-R$I&gt;$\0@\W/VW&lt;[_"\Y[X&amp;],0^^+,]T_J&gt;`J@_B_]'_.T`$KO.@I"XC-_N!!!!!!</Property>
<Property Name="NI.Lib.SourceVersion" Type="Int">419463168</Property>
<Property Name="NI.Lib.Version" Type="Str">1.0.0.0</Property>
<Property Name="NI.LV.All.SourceOnly" Type="Bool">false</Property>
<Item Name="binarySearch.vi" Type="VI" URL="../binarySearch.vi"/>
<Item Name="Close.vi" Type="VI" URL="../Close.vi"/>
<Item Name="example.vi" Type="VI" URL="../example.vi"/>
<Item Name="Get data.vi" Type="VI" URL="../Get data.vi"/>
<Item Name="ip2region.ctl" Type="VI" URL="../ip2region.ctl"/>
<Item Name="Open.vi" Type="VI" URL="../Open.vi"/>
</Library>

View File

@ -1,7 +0,0 @@
ip2region的LabVIEW库<br>
使用方法1. 将该目录下的所有文件复制到你的项目文件夹下;<br>
2. 导入ip2region.lvlib库文件<br>
3. 查看Example.vi了解使用方法<br>
<br>
<br>
注意该库依赖ni_lib_unicode-2.0.1.5.vip请使用VIPM安装。

View File

@ -1,54 +0,0 @@
using BenchmarkDotNet.Attributes;
using IP2Region.Models;
using System.Threading.Tasks;
namespace IP2Region.Test.Benchmark
{
[RankColumn]
public class DbSearch_Test : TestBase
{
private string RandomIP = "";
[Benchmark]
public DataBlock MemorySearch()
{
RandomIP = GetRandomIP();
return _search.MemorySearch(RandomIP);
}
[Benchmark]
public async Task<DataBlock> MemorySearch_Async()
{
RandomIP = GetRandomIP();
return await _search.MemorySearchAsync(RandomIP);
}
[Benchmark]
public DataBlock BinarySearch()
{
RandomIP = GetRandomIP();
return _search.BinarySearch(RandomIP);
}
[Benchmark]
public async Task<DataBlock> BinarySearch_Async()
{
RandomIP = GetRandomIP();
return await _search.BinarySearchAsync(RandomIP);
}
[Benchmark]
public DataBlock BtreeSearch()
{
RandomIP = GetRandomIP();
return _search.BtreeSearch(RandomIP);
}
[Benchmark]
public async Task<DataBlock> BtreeSearch_Async()
{
RandomIP = GetRandomIP();
return await _search.BtreeSearchAsync(RandomIP);
}
}
}

View File

@ -1,16 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.11.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\IP2Region\IP2Region.csproj" />
</ItemGroup>
</Project>

View File

@ -1,15 +0,0 @@
using BenchmarkDotNet.Running;
using System;
namespace IP2Region.Test.Benchmark
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Now starting benchmark test, please wait......");
var summary = BenchmarkRunner.Run<DbSearch_Test>();
Console.ReadLine();
}
}
}

View File

@ -1,49 +0,0 @@
using BenchmarkDotNet.Attributes;
using System;
namespace IP2Region.Test.Benchmark
{
public class TestBase
{
protected DbSearcher _search;
private readonly string _dBFilePath = "";
public TestBase()
{
}
public TestBase(String DBFilePath)
{
_dBFilePath = DBFilePath;
}
[GlobalSetup]
public void Init()
{
if (String.IsNullOrEmpty(_dBFilePath))
{
_search = new DbSearcher(AppContext.BaseDirectory + @"\DB\ip2region.db");
}
else
{
_search = new DbSearcher(_dBFilePath);
}
}
[GlobalCleanup]
public void Dispose()
{
_search.Dispose();
}
public String GetRandomIP()
{
return new Random(Guid.NewGuid().GetHashCode()).Next(0, 255).ToString() + "."
+ new Random(Guid.NewGuid().GetHashCode()).Next(0, 255).ToString() + "."
+ new Random(Guid.NewGuid().GetHashCode()).Next(0, 255).ToString() + "."
+ new Random(Guid.NewGuid().GetHashCode()).Next(0, 255).ToString();
}
}
}

View File

@ -1,26 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.7.0" />
<PackageReference Include="xunit" Version="2.3.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" />
<DotNetCliToolReference Include="dotnet-xunit" Version="2.3.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\IP2Region\IP2Region.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="DB\ip2region.db">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -1,74 +0,0 @@
using System;
using System.Threading.Tasks;
using Xunit;
namespace IP2Region.Test.xUnit
{
public class SearchTest : IDisposable
{
private readonly DbSearcher _search;
public String GetRandomIP()
{
return new Random(Guid.NewGuid().GetHashCode()).Next(0, 255).ToString() + "."
+ new Random(Guid.NewGuid().GetHashCode()).Next(0, 255).ToString() + "."
+ new Random(Guid.NewGuid().GetHashCode()).Next(0, 255).ToString() + "."
+ new Random(Guid.NewGuid().GetHashCode()).Next(0, 255).ToString();
}
public SearchTest()
{
_search = new DbSearcher(Environment.CurrentDirectory + @"\DB\ip2region.db");
}
[Fact]
public void Search_Test()
{
string memResult = _search.MemorySearch("223.104.246.20").Region;
string binarySearchResult = _search.BinarySearch("223.104.246.20").Region;
string binaryTreeSearchResult = _search.BtreeSearch("223.104.246.20").Region;
Assert.NotNull(memResult);
Assert.NotNull(binarySearchResult);
Assert.NotNull(binaryTreeSearchResult);
Assert.Equal(memResult, binarySearchResult);
Assert.Equal(binaryTreeSearchResult, memResult);
}
[Fact]
public void Search_Correct_Test()
{
for (int i = 0; i < 1000000; i++)
{
var newIp=GetRandomIP();
string memResult = _search.MemorySearch(newIp).Region;
string binarySearchResult = _search.BinarySearch(newIp).Region;
string binaryTreeSearchResult = _search.BtreeSearch(newIp).Region;
Assert.True(memResult == binarySearchResult && memResult == binaryTreeSearchResult);
}
}
[Fact]
public async Task SearchAsync_Test()
{
// We don't need the synchronizeContext, so just set to false
var memResult = await _search.MemorySearchAsync("183.192.62.65").ConfigureAwait(false);
var binarySearchResult = await _search.BinarySearchAsync("183.192.62.65").ConfigureAwait(false);
var bTreeSearchResult = await _search.BtreeSearchAsync("183.192.62.65").ConfigureAwait(false);
Assert.NotNull(memResult.Region);
Assert.NotNull(binarySearchResult.Region);
Assert.NotNull(bTreeSearchResult.Region);
Assert.Equal(memResult.Region, binarySearchResult.Region);
Assert.Equal(bTreeSearchResult.Region, memResult.Region);
}
public void Dispose()
{
_search.Dispose();
}
}
}

Binary file not shown.

View File

@ -1,412 +0,0 @@
//*******************************
// Created By Rocher Kong
// Github https://github.com/RocherKong
// Date 2018.02.09
//*******************************
using IP2Region.Models;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace IP2Region
{
public class DbSearcher : IDisposable
{
const int BTREE_ALGORITHM = 1;
const int BINARY_ALGORITHM = 2;
const int MEMORY_ALGORITYM = 3;
private DbConfig _dbConfig = null;
/// <summary>
/// db file access handler
/// </summary>
private Stream _raf = null;
/// <summary>
/// header blocks buffer
/// </summary>
private long[] _headerSip = null;
private int[] _headerPtr = null;
private int _headerLength;
/// <summary>
/// super blocks info
/// </summary>
private long _firstIndexPtr = 0;
private long _lastIndexPtr = 0;
private int _totalIndexBlocks = 0;
/// <summary>
/// for memory mode
/// the original db binary string
/// </summary>
private byte[] _dbBinStr = null;
/// <summary>
/// Get by index ptr.
/// </summary>
private DataBlock GetByIndexPtr(long ptr)
{
_raf.Seek(ptr, SeekOrigin.Begin);
byte[] buffer = new byte[12];
_raf.Read(buffer, 0, buffer.Length);
long extra = Utils.GetIntLong(buffer, 8);
int dataLen = (int)((extra >> 24) & 0xFF);
int dataPtr = (int)((extra & 0x00FFFFFF));
_raf.Seek(dataPtr, SeekOrigin.Begin);
byte[] data = new byte[dataLen];
_raf.Read(data, 0, data.Length);
int city_id = (int)Utils.GetIntLong(data, 0);
string region = Encoding.UTF8.GetString(data, 4, data.Length - 4);
return new DataBlock(city_id, region, dataPtr);
}
public DbSearcher(DbConfig dbConfig, string dbFile)
{
if (_dbConfig == null)
{
_dbConfig = dbConfig;
}
_raf = new FileStream(dbFile, FileMode.Open, FileAccess.Read, FileShare.Read);
}
public DbSearcher(string dbFile) : this(null, dbFile) { }
public DbSearcher(DbConfig dbConfig, Stream dbFileStream)
{
if (_dbConfig == null)
{
_dbConfig = dbConfig;
}
_raf = dbFileStream;
}
public DbSearcher(Stream dbFileStream) : this(null, dbFileStream) { }
#region Sync Methods
/// <summary>
/// Get the region with a int ip address with memory binary search algorithm.
/// </summary>
private DataBlock MemorySearch(long ip)
{
int blen = IndexBlock.LENGTH;
if (_dbBinStr == null)
{
_dbBinStr = new byte[(int)_raf.Length];
_raf.Seek(0L, SeekOrigin.Begin);
_raf.Read(_dbBinStr, 0, _dbBinStr.Length);
//initialize the global vars
_firstIndexPtr = Utils.GetIntLong(_dbBinStr, 0);
_lastIndexPtr = Utils.GetIntLong(_dbBinStr, 4);
_totalIndexBlocks = (int)((_lastIndexPtr - _firstIndexPtr) / blen) + 1;
}
//search the index blocks to define the data
int l = 0, h = _totalIndexBlocks;
long sip = 0;
while (l <= h)
{
int m = (l + h) >> 1;
int p = (int)(_firstIndexPtr + m * blen);
sip = Utils.GetIntLong(_dbBinStr, p);
if (ip < sip)
{
h = m - 1;
}
else
{
sip = Utils.GetIntLong(_dbBinStr, p + 4);
if (ip > sip)
{
l = m + 1;
}
else
{
sip = Utils.GetIntLong(_dbBinStr, p + 8);
break;
}
}
}
//not matched
if (sip == 0) return null;
//get the data
int dataLen = (int)((sip >> 24) & 0xFF);
int dataPtr = (int)((sip & 0x00FFFFFF));
int city_id = (int)Utils.GetIntLong(_dbBinStr, dataPtr);
string region = Encoding.UTF8.GetString(_dbBinStr, dataPtr + 4, dataLen - 4);//new String(dbBinStr, dataPtr + 4, dataLen - 4, Encoding.UTF8);
return new DataBlock(city_id, region, dataPtr);
}
/// <summary>
/// Get the region throught the ip address with memory binary search algorithm.
/// </summary>
public DataBlock MemorySearch(string ip)
{
return MemorySearch(Utils.Ip2long(ip));
}
/// <summary>
/// Get the region with a int ip address with b-tree algorithm.
/// </summary>
private DataBlock BtreeSearch(long ip)
{
//check and load the header
if (_headerSip == null)
{
_raf.Seek(8L, SeekOrigin.Begin); //pass the super block
byte[] b = new byte[4096];
_raf.Read(b, 0, b.Length);
//fill the header
int len = b.Length >> 3, idx = 0; //b.lenght / 8
_headerSip = new long[len];
_headerPtr = new int[len];
long startIp, dataPtrTemp;
for (int i = 0; i < b.Length; i += 8)
{
startIp = Utils.GetIntLong(b, i);
dataPtrTemp = Utils.GetIntLong(b, i + 4);
if (dataPtrTemp == 0) break;
_headerSip[idx] = startIp;
_headerPtr[idx] = (int)dataPtrTemp;
idx++;
}
_headerLength = idx;
}
//1. define the index block with the binary search
if (ip == _headerSip[0])
{
return GetByIndexPtr(_headerPtr[0]);
}
else if (ip == _headerPtr[_headerLength - 1])
{
return GetByIndexPtr(_headerPtr[_headerLength - 1]);
}
int l = 0, h = _headerLength, sptr = 0, eptr = 0;
int m = 0;
while (l <= h)
{
m = (l + h) >> 1;
//perfectly matched, just return it
if (ip == _headerSip[m])
{
if (m > 0)
{
sptr = _headerPtr[m - 1];
eptr = _headerPtr[m];
}
else
{
sptr = _headerPtr[m];
eptr = _headerPtr[m + 1];
}
}
//less then the middle value
else if (ip < _headerSip[m])
{
if (m == 0)
{
sptr = _headerPtr[m];
eptr = _headerPtr[m + 1];
break;
}
else if (ip > _headerSip[m - 1])
{
sptr = _headerPtr[m - 1];
eptr = _headerPtr[m];
break;
}
h = m - 1;
}
else
{
if (m == _headerLength - 1)
{
sptr = _headerPtr[m - 1];
eptr = _headerPtr[m];
break;
}
else if (ip <= _headerSip[m + 1])
{
sptr = _headerPtr[m];
eptr = _headerPtr[m + 1];
break;
}
l = m + 1;
}
}
//match nothing just stop it
if (sptr == 0) return null;
//2. search the index blocks to define the data
int blockLen = eptr - sptr, blen = IndexBlock.LENGTH;
byte[] iBuffer = new byte[blockLen + blen]; //include the right border block
_raf.Seek(sptr, SeekOrigin.Begin);
_raf.Read(iBuffer, 0, iBuffer.Length);
l = 0; h = blockLen / blen;
long sip = 0;
int p = 0;
while (l <= h)
{
m = (l + h) >> 1;
p = m * blen;
sip = Utils.GetIntLong(iBuffer, p);
if (ip < sip)
{
h = m - 1;
}
else
{
sip = Utils.GetIntLong(iBuffer, p + 4);
if (ip > sip)
{
l = m + 1;
}
else
{
sip = Utils.GetIntLong(iBuffer, p + 8);
break;
}
}
}
//not matched
if (sip == 0) return null;
//3. get the data
int dataLen = (int)((sip >> 24) & 0xFF);
int dataPtr = (int)((sip & 0x00FFFFFF));
_raf.Seek(dataPtr, SeekOrigin.Begin);
byte[] data = new byte[dataLen];
_raf.Read(data, 0, data.Length);
int city_id = (int)Utils.GetIntLong(data, 0);
String region = Encoding.UTF8.GetString(data, 4, data.Length - 4);// new String(data, 4, data.Length - 4, "UTF-8");
return new DataBlock(city_id, region, dataPtr);
}
/// <summary>
/// Get the region throught the ip address with b-tree search algorithm.
/// </summary>
public DataBlock BtreeSearch(string ip)
{
return BtreeSearch(Utils.Ip2long(ip));
}
/// <summary>
/// Get the region with a int ip address with binary search algorithm.
/// </summary>
private DataBlock BinarySearch(long ip)
{
int blen = IndexBlock.LENGTH;
if (_totalIndexBlocks == 0)
{
_raf.Seek(0L, SeekOrigin.Begin);
byte[] superBytes = new byte[8];
_raf.Read(superBytes, 0, superBytes.Length);
//initialize the global vars
_firstIndexPtr = Utils.GetIntLong(superBytes, 0);
_lastIndexPtr = Utils.GetIntLong(superBytes, 4);
_totalIndexBlocks = (int)((_lastIndexPtr - _firstIndexPtr) / blen) + 1;
}
//search the index blocks to define the data
int l = 0, h = _totalIndexBlocks;
byte[] buffer = new byte[blen];
long sip = 0;
while (l <= h)
{
int m = (l + h) >> 1;
_raf.Seek(_firstIndexPtr + m * blen, SeekOrigin.Begin); //set the file pointer
_raf.Read(buffer, 0, buffer.Length);
sip = Utils.GetIntLong(buffer, 0);
if (ip < sip)
{
h = m - 1;
}
else
{
sip = Utils.GetIntLong(buffer, 4);
if (ip > sip)
{
l = m + 1;
}
else
{
sip = Utils.GetIntLong(buffer, 8);
break;
}
}
}
//not matched
if (sip == 0) return null;
//get the data
int dataLen = (int)((sip >> 24) & 0xFF);
int dataPtr = (int)((sip & 0x00FFFFFF));
_raf.Seek(dataPtr, SeekOrigin.Begin);
byte[] data = new byte[dataLen];
_raf.Read(data, 0, data.Length);
int city_id = (int)Utils.GetIntLong(data, 0);
String region = Encoding.UTF8.GetString(data, 4, data.Length - 4);//new String(data, 4, data.Length - 4, "UTF-8");
return new DataBlock(city_id, region, dataPtr);
}
/// <summary>
/// Get the region throught the ip address with binary search algorithm.
/// </summary>
public DataBlock BinarySearch(String ip)
{
return BinarySearch(Utils.Ip2long(ip));
}
#endregion
#region Async Methods
/// <summary>
/// Get the region throught the ip address with memory binary search algorithm.
/// </summary>
public Task<DataBlock> MemorySearchAsync(string ip)
{
return Task.FromResult(MemorySearch(ip));
}
/// <summary>
/// Get the region throught the ip address with b-tree search algorithm.
/// </summary>
public Task<DataBlock> BtreeSearchAsync(string ip)
{
return Task.FromResult(BtreeSearch(ip));
}
/// <summary>
/// Get the region throught the ip address with binary search algorithm.
/// </summary>
public Task<DataBlock> BinarySearchAsync(string ip)
{
return Task.FromResult(BinarySearch(ip));
}
#endregion
/// <summary>
/// Close the db.
/// </summary>
public void Close()
{
_headerSip = null;
_headerPtr = null;
_dbBinStr = null;
_raf.Close();
}
public void Dispose()
{
Close();
}
}
}

View File

@ -1,26 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net46;net45;net47</TargetFrameworks>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Authors>Rocher</Authors>
<Company>Rocher</Company>
<Description>准确率99.9%的ip地址定位库0.0x毫秒级查询, 支持Binary,B树,内存三种查询算法妈妈再也不用担心我的ip地址定位</Description>
<PackageReleaseNotes>ip2region - 最自由的ip地址查询库ip到地区的映射库提供Binary,B树和纯内存三种查询算法妈妈再也不用担心我的ip地址定位。</PackageReleaseNotes>
<Copyright>Rocher</Copyright>
<PackageTags>ip2region c# IP</PackageTags>
<RepositoryUrl>https://gitee.com/rocherkong/IP2Region</RepositoryUrl>
<Version>1.2.0</Version>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|netstandard2.0|AnyCPU'">
<LangVersion>7</LangVersion>
</PropertyGroup>
<ItemGroup>
<None Update="DB\ip2region.db">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -1,50 +0,0 @@
//*******************************
// Created By Rocher Kong
// Github https://github.com/RocherKong
// Date 2018.02.09
//*******************************
namespace IP2Region.Models
{
public class DataBlock
{
#region Private Properties
public int CityID
{
get;
private set;
}
public string Region
{
get;
private set;
}
public int DataPtr
{
get;
private set;
}
#endregion
#region Constructor
public DataBlock(int city_id, string region, int dataPtr = 0)
{
CityID = city_id;
Region = region;
DataPtr = dataPtr;
}
public DataBlock(int city_id, string region):this(city_id,region,0)
{
}
#endregion
public override string ToString()
{
return $"{CityID}|{Region}|{DataPtr}";
}
}
}

View File

@ -1,49 +0,0 @@
//*******************************
// Created By Rocher Kong
// Github https://github.com/RocherKong
// Date 2018.02.09
//*******************************
using System;
namespace IP2Region.Models
{
public class DbMakerConfigException : Exception
{
public string ErrMsg { get; private set; }
public DbMakerConfigException(string errMsg)
{
ErrMsg = errMsg;
}
}
public class DbConfig
{
public int TotalHeaderSize
{
get;
private set;
}
public int indexBlockSize
{
get;
private set;
}
public DbConfig(int totalHeaderSize)
{
if ((totalHeaderSize % 8) != 0)
{
throw new DbMakerConfigException("totalHeaderSize must be times of 8");
}
TotalHeaderSize = totalHeaderSize;
//4 * 2048
indexBlockSize = 8192;
}
public DbConfig():this(8 * 2048)
{
}
}
}

View File

@ -1,49 +0,0 @@
//*******************************
// Created By Rocher Kong
// Github https://github.com/RocherKong
// Date 2018.02.09
//*******************************
namespace IP2Region.Models
{
internal class HeaderBlock
{
public long IndexStartIp
{
get;
private set;
}
public int IndexPtr
{
get;
private set;
}
public HeaderBlock(long indexStartIp, int indexPtr)
{
IndexStartIp = indexStartIp;
IndexPtr = indexPtr;
}
/// <summary>
/// Get the bytes for total storage
/// </summary>
/// <returns>
/// Bytes gotten.
/// </returns>
public byte[] GetBytes()
{
/*
* +------------+-----------+
* | 4bytes | 4bytes |
* +------------+-----------+
* start ip index ptr
*/
byte[] b = new byte[8];
Utils.WriteIntLong(b, 0, IndexStartIp);
Utils.WriteIntLong(b, 4, IndexPtr);
return b;
}
}
}

View File

@ -1,65 +0,0 @@
//*******************************
// Created By Rocher Kong
// Github https://github.com/RocherKong
// Date 2018.02.09
//*******************************
namespace IP2Region
{
internal class IndexBlock
{
public const int LENGTH = 12;
public long StartIP
{
get;
private set;
}
public long EndIp
{
get;
private set;
}
public uint DataPtr
{
get;
private set;
}
public int DataLen
{
get;
private set;
}
public IndexBlock(long startIp, long endIp, uint dataPtr, int dataLen)
{
StartIP = startIp;
EndIp = endIp;
DataPtr = dataPtr;
DataLen = dataLen;
}
public byte[] GetBytes()
{
/*
* +------------+-----------+-----------+
* | 4bytes | 4bytes | 4bytes |
* +------------+-----------+-----------+
* start ip end ip data ptr + len
*/
byte[] b = new byte[12];
Utils.WriteIntLong(b, 0, StartIP); //start ip
Utils.WriteIntLong(b, 4, EndIp); //end ip
//write the data ptr and the length
long mix = DataPtr | ((DataLen << 24) & 0xFF000000L);
Utils.WriteIntLong(b, 8, mix);
return b;
}
}
}

View File

@ -1,122 +0,0 @@
//*******************************
// Created By Rocher Kong
// Github https://github.com/RocherKong
// Date 2018.02.09
//*******************************
using System;
namespace IP2Region
{
public class IPInValidException : Exception
{
const string ERROR_MSG = "IP Illigel. Please input a valid IP.";
public IPInValidException() : base(ERROR_MSG) { }
}
internal static class Utils
{
/// <summary>
/// Write specfield bytes to a byte array start from offset.
/// </summary>
public static void Write(byte[] b, int offset, ulong v, int bytes)
{
for (int i = 0; i < bytes; i++)
{
b[offset++] = (byte)((v >> (8 * i)) & 0xFF);
}
}
/// <summary>
/// Write a int to a byte array.
/// </summary>
public static void WriteIntLong(byte[] b, int offset, long v)
{
b[offset++] = (byte)((v >> 0) & 0xFF);
b[offset++] = (byte)((v >> 8) & 0xFF);
b[offset++] = (byte)((v >> 16) & 0xFF);
b[offset] = (byte)((v >> 24) & 0xFF);
}
/// <summary>
/// Get a int from a byte array start from the specifiled offset.
/// </summary>
public static long GetIntLong(byte[] b, int offset)
{
return (
((b[offset++] & 0x000000FFL)) |
((b[offset++] << 8) & 0x0000FF00L) |
((b[offset++] << 16) & 0x00FF0000L) |
((b[offset] << 24) & 0xFF000000L)
);
}
/// <summary>
/// Get a int from a byte array start from the specifield offset.
/// </summary>
public static int GetInt3(byte[] b, int offset)
{
return (
(b[offset++] & 0x000000FF) |
(b[offset++] & 0x0000FF00) |
(b[offset] & 0x00FF0000)
);
}
public static int GetInt2(byte[] b, int offset)
{
return (
(b[offset++] & 0x000000FF) |
(b[offset] & 0x0000FF00)
);
}
public static int GetInt1(byte[] b, int offset)
{
return (
(b[offset] & 0x000000FF)
);
}
/// <summary>
/// String ip to long ip.
/// </summary>
public static long Ip2long(string ip)
{
string[] p = ip.Split('.');
if (p.Length != 4) throw new IPInValidException();
foreach (string pp in p)
{
if (pp.Length > 3) throw new IPInValidException();
if (!int.TryParse(pp, out int value) || value > 255)
{
throw new IPInValidException();
}
}
var bip1 = long.TryParse(p[0], out long ip1);
var bip2 = long.TryParse(p[1], out long ip2);
var bip3 = long.TryParse(p[2], out long ip3);
var bip4 = long.TryParse(p[3], out long ip4);
if (!bip1 || !bip2 || !bip3 || !bip4
|| ip4 > 255 || ip1 > 255 || ip2 > 255 || ip3 > 255
|| ip4 < 0 || ip1 < 0 || ip2 < 0 || ip3 < 0)
{
throw new IPInValidException();
}
long p1 = ((ip1 << 24) & 0xFF000000);
long p2 = ((ip2 << 16) & 0x00FF0000);
long p3 = ((ip3 << 8) & 0x0000FF00);
long p4 = ((ip4 << 0) & 0x000000FF);
return ((p1 | p2 | p3 | p4) & 0xFFFFFFFFL);
}
/// <summary>
/// Int to ip string.
/// </summary>
public static string Long2ip(long ip)
{
return $"{(ip >> 24) & 0xFF}.{(ip >> 16) & 0xFF}.{(ip >> 8) & 0xFF}.{ip & 0xFF}";
}
}
}

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

View File

@ -1,60 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{2D73D7EB-AE36-4039-A839-DA40209052A4}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>IP2Region_NetFx_Test</RootNamespace>
<AssemblyName>IP2Region_NetFx_Test</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="DB\ip2region.db">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\IP2Region\IP2Region.csproj">
<Project>{a27d09f4-4da8-4925-90ec-43e5f5288630}</Project>
<Name>IP2Region</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -1,17 +0,0 @@
using IP2Region;
using System;
namespace IP2Region_NetFx_Test
{
class Program
{
static void Main(string[] args)
{
using (var _search = new DbSearcher(Environment.CurrentDirectory + @"\DB\ip2region.db"))
{
Console.WriteLine(_search.MemorySearch("183.192.62.65").Region);
Console.Read();
}
}
}
}

View File

@ -1,35 +0,0 @@
using System.Reflection;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("IP2Region_NetFx_Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IP2Region_NetFx_Test")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("2d73d7eb-ae36-4039-a839-da40209052a4")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -1,42 +0,0 @@
# IP2Region C# Client
## How To Use
### 1.Install from Nuget. Support .Net Framework (>=4.5) And netstandard 2.0(.net core)
```powershell
Install-Package IP2Region
```
### 2.Init DbSearcher with [the newest DBFile](https://github.com/lionsoul2014/ip2region/blob/master/data/ip2region.db) Downloaded into your project, and invoke your search methods as below:
```csharp
using (var _search = new DbSearcher(Environment.CurrentDirectory + @"\DB\ip2region.db"))
{
_search.MemorySearch("183.192.62.65").Region;
_search.BinarySearch("183.192.62.65").Region;
_search.BtreeSearch("183.192.62.65").Region;
}
```
For async methods (Methods with the suffix "Async"), just put them with `async` and `await`.
If you don't need the `SynchronizedContext`, please use `ConfigureAwait(false)`.
For more about this, please read https://msdn.microsoft.com/en-us/magazine/jj991977.aspx.
```csharp
public async Task SearchAsync_Test()
{
// We don't need the synchronizeContext, so just set to false.
// So as for BinarySearchAsync and BtreeSearchAsync
var memResult = await _search.MemorySearchAsync("183.192.62.65").ConfigureAwait(false);
}
```
## Test Result(From /IP2Region.Test.Benchmark)
Method | Mean | Error | StdDev | Rank |
------------------- |---------: |----------: |----------: |-----: |
MemorySearch | 10.66 us | 0.1424 us | 0.1332 us | 1 |
MemorySearch_Async | 10.90 us | 0.2060 us | 0.2023 us | 2 |
BinarySearch | 52.22 us | 0.6403 us | 0.5347 us | 5 |
BinarySearch_Async | 53.03 us | 1.0271 us | 0.9608 us | 6 |
BtreeSearch | 19.05 us | 0.2464 us | 0.2305 us | 3 |
BtreeSearch_Async | 19.40 us | 0.3820 us | 0.6690 us | 4 |
Because the speed of the program lookup has been fast, the asynchronous method here is just the packaging of the synchronization method, the essence is the synchronization method, the asynchronous method is not recommended, and asynchronous will bring the performance loss, unless you need the asynchronous call format.

View File

@ -1,26 +0,0 @@
A = @
CFLAGS= -g
CC= gcc
LIBS= -I./
LDFLAGS=
RM = rm -f
MV = mv
testSearcher: ip2region.o
$(A) $(CC) $(CFLAGS) $(LDFLAGS) $(LIBS) -o testSearcher testSearcher.c ip2region.c
$(A) $(RM) ip2region.o testSearcher.o
db:
$(A) cd ../../;\
export LANG=en_US.UTF-8;\
java -jar dbMaker-1.2.2.jar -src ./data/ip.merge.txt -region ./data/global_region.csv -dst .;\
$(MV) ./ip2region.db ./binding/c/;\
cd ./binding/c
all: db testSearcher
clean:
$(A) $(RM) testSearcher
.PHONY: all clean testSearcher db

View File

@ -1,441 +0,0 @@
/**
* default ip2region implementation
*
* @see #ip2region.h
* @author chenxin<chenxin619315@gmail.com>
* @date 2015-10-30
*/
#include "ip2region.h"
#include <stdio.h>
#include <stdlib.h>
/**
* create a new ip2region object
*
* @param dbFile path
*/
IP2R_API uint_t ip2region_create(ip2region_t ip2rObj, const char *dbFile)
{
memset(ip2rObj, 0x00, sizeof(ip2region_entry));
ip2rObj->headerLen = 0;
ip2rObj->HeaderSip = (uint_t *) IP2R_MALLOC(TOTAL_HEADER_LENGTH);
if ( ip2rObj->HeaderSip == NULL ) {
return 0;
}
ip2rObj->HeaderPtr = (uint_t *) IP2R_MALLOC(TOTAL_HEADER_LENGTH);
if ( ip2rObj->HeaderPtr == NULL ) {
IP2R_FREE(ip2rObj->HeaderSip);
return 0;
}
//open the db file
ip2rObj->dbHandler = fopen(dbFile, "rb");
if ( ip2rObj->dbHandler == NULL ) {
IP2R_FREE(ip2rObj->HeaderSip);
IP2R_FREE(ip2rObj->HeaderPtr);
//fprintf(stderr, "Fail to open the db file %s\n", ip2rObj>dbFile);
//exit(-1);
return 0;
}
ip2rObj->firstIndexPtr = 0;
ip2rObj->lastIndexPtr = 0;
ip2rObj->totalBlocks = 0;
ip2rObj->dbBinStr = NULL;
return 1;
}
/**
* destroy the specifield ip2region object
*
* @param ip2region_t
*/
IP2R_API uint_t ip2region_destroy(ip2region_t ip2rObj)
{
if ( ip2rObj->HeaderSip != NULL ) {
IP2R_FREE(ip2rObj->HeaderSip);
ip2rObj->HeaderSip = NULL;
}
if ( ip2rObj->HeaderPtr != NULL ) {
IP2R_FREE(ip2rObj->HeaderPtr);
ip2rObj->HeaderPtr = NULL;
}
// close the db file resource
if ( ip2rObj->dbHandler != NULL ) {
fclose(ip2rObj->dbHandler);
ip2rObj->dbHandler = NULL;
}
// free the db binary string
if ( ip2rObj->dbBinStr != NULL ) {
IP2R_FREE(ip2rObj->dbBinStr);
ip2rObj->dbBinStr = NULL;
}
return 1;
}
/**
* get the region associated with the specified ip address with the memory binary search algorithm
*
* @param ip2rObj
* @param ip
* @param datablock
*/
IP2R_API uint_t ip2region_memory_search(ip2region_t ip2rObj, uint_t ip, datablock_t datablock)
{
int l, h, m, p;
uint_t sip, eip, dptr;
int dataLen, dataptr;
long filesize;
char *buffer;
if ( ip2rObj->dbBinStr == NULL ) {
//get the size of the file
fseek(ip2rObj->dbHandler, 0, SEEK_END);
filesize = ftell(ip2rObj->dbHandler);
fseek(ip2rObj->dbHandler, 0, SEEK_SET);
//alloc the buffer size
ip2rObj->dbBinStr = IP2R_MALLOC(filesize);
if ( ip2rObj->dbBinStr == NULL ) {
return 0;
}
//now read the whole file
if ( fread(ip2rObj->dbBinStr, filesize, 1, ip2rObj->dbHandler) != 1 ) {
return 0;
}
buffer = ip2rObj->dbBinStr;
ip2rObj->firstIndexPtr = getUnsignedInt(buffer, 0);
ip2rObj->lastIndexPtr = getUnsignedInt(buffer, 4);
ip2rObj->totalBlocks = (ip2rObj->lastIndexPtr-ip2rObj->firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
}
l = 0; h = ip2rObj->totalBlocks; dptr = 0;
while ( l <= h ) {
m = (l + h) >> 1;
p = ip2rObj->firstIndexPtr + m * INDEX_BLOCK_LENGTH;
buffer = ip2rObj->dbBinStr + p;
sip = getUnsignedInt(buffer, 0);
if ( ip < sip ) {
h = m - 1;
} else {
eip = getUnsignedInt(buffer, 4);
if ( ip > eip ) {
l = m + 1;
} else {
dptr = getUnsignedInt(buffer, 8);
break;
}
}
}
if ( dptr == 0 ) return 0;
//get the data
dataLen = ((dptr >> 24) & 0xFF);
dataptr = (dptr & 0x00FFFFFF);
buffer = ip2rObj->dbBinStr + dataptr;
//fill the data to the datablock
datablock->city_id = getUnsignedInt(buffer, 0);
dataLen -= 4; //reduce the length of the city_id
memcpy(datablock->region, buffer + 4, dataLen);
datablock->region[dataLen] = '\0';
return 1;
}
IP2R_API uint_t ip2region_memory_search_string(ip2region_t ip2rObj, const char *ip, datablock_t datablock)
{
return ip2region_memory_search(ip2rObj, ip2long(ip), datablock);
}
/**
* get the region associated with the specifield ip address with binary search algorithm
*
* @param ip2rObj
* @param ip
* @param datablock
* @return uint_t
*/
IP2R_API uint_t ip2region_binary_search(ip2region_t ip2rObj, uint_t ip, datablock_t datablock)
{
int l, h, m, p;
uint_t sip, eip, dptr;
char buffer[256];
int dataLen, dataptr;
if ( ip2rObj->totalBlocks == 0 ) {
fseek(ip2rObj->dbHandler, 0, 0);
if ( fread(buffer, 8, 1, ip2rObj->dbHandler) != 1 ) {
return 0;
}
ip2rObj->firstIndexPtr = getUnsignedInt(buffer, 0);
ip2rObj->lastIndexPtr = getUnsignedInt(buffer, 4);
ip2rObj->totalBlocks = (ip2rObj->lastIndexPtr-ip2rObj->firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
}
//binary search the index blocks to define the data block
l = 0; h = ip2rObj->totalBlocks; dptr = 0;
while ( l <= h ) {
m = (l + h) >> 1;
p = ip2rObj->firstIndexPtr + m * INDEX_BLOCK_LENGTH;
fseek(ip2rObj->dbHandler, p, 0);
if ( fread(buffer, INDEX_BLOCK_LENGTH, 1, ip2rObj->dbHandler) != 1 ) {
return 0;
}
sip = getUnsignedInt(buffer, 0);
if ( ip < sip ) {
h = m - 1;
} else {
eip = getUnsignedInt(buffer, 4);
if ( ip > eip ) {
l = m + 1;
} else {
dptr = getUnsignedInt(buffer, 8);
break;
}
}
}
if ( dptr == 0 ) return 0;
//get the data
dataLen = ((dptr >> 24) & 0xFF);
dataptr = (dptr & 0x00FFFFFF);
//memset(data, 0x00, sizeof(data));
fseek(ip2rObj->dbHandler, dataptr, 0);
if ( fread(buffer, dataLen, 1, ip2rObj->dbHandler) != 1 ) {
return 0;
}
//fill the data to the datablock
datablock->city_id = getUnsignedInt(buffer, 0);
dataLen -= 4; //reduce the length of the city_id
memcpy(datablock->region, buffer + 4, dataLen);
datablock->region[dataLen] = '\0';
return 1;
}
IP2R_API uint_t ip2region_binary_search_string(ip2region_t ip2rObj, const char *ip, datablock_t datablock)
{
return ip2region_binary_search(ip2rObj, ip2long(ip), datablock);
}
/**
* get the region associated with the specifield ip address with b-tree algorithm
*
* @param ip2rObj
* @param ip
* @param datablock
* @return uint_t
*/
IP2R_API uint_t ip2region_btree_search(ip2region_t ip2rObj, uint_t ip, datablock_t datablock)
{
int i, idx;
int l, m, h, p, sptr, eptr, indexBlockLen, dataLen, dataptr;
uint_t sip, eip, idxptr, dptr;
char buffer[TOTAL_HEADER_LENGTH];
if ( ip2rObj->headerLen == 0 ) {
idx = 0;
fseek(ip2rObj->dbHandler, 8, 0); //pass the super block
if ( fread(buffer, TOTAL_HEADER_LENGTH, 1, ip2rObj->dbHandler) != 1 ) {
return 0;
}
for ( i = 0; i < TOTAL_HEADER_LENGTH; i += 8 ) {
sip = getUnsignedInt(buffer, i);
idxptr = getUnsignedInt(buffer, i + 4);
if ( idxptr == 0 ) break;
ip2rObj->HeaderSip[idx] = sip;
ip2rObj->HeaderPtr[idx] = idxptr;
idx++;
}
ip2rObj->headerLen = idx;
}
//search the header block to define the index block
l = 0; h = ip2rObj->headerLen; sptr = 0; eptr = 0;
while ( l <= h ) {
m = ((l + h) >> 1);
//perfetc matched, just return it
if ( ip == ip2rObj->HeaderSip[m] ) {
if ( m > 0 ) {
sptr = ip2rObj->HeaderPtr[m-1];
eptr = ip2rObj->HeaderPtr[m ];
} else {
sptr = ip2rObj->HeaderPtr[m ];
eptr = ip2rObj->HeaderPtr[m+1];
}
break;
}
//less then the middle value
if ( ip < ip2rObj->HeaderSip[m] ) {
if ( m == 0 ) {
sptr = ip2rObj->HeaderPtr[m ];
eptr = ip2rObj->HeaderPtr[m+1];
break;
} else if ( ip > ip2rObj->HeaderSip[m-1] ) {
sptr = ip2rObj->HeaderPtr[m-1];
eptr = ip2rObj->HeaderPtr[m ];
break;
}
h = m - 1;
} else {
if ( m == ip2rObj->headerLen - 1 ) {
sptr = ip2rObj->HeaderPtr[m-1];
eptr = ip2rObj->HeaderPtr[m ];
break;
} else if ( ip <= ip2rObj->HeaderSip[m+1] ) {
sptr = ip2rObj->HeaderPtr[m ];
eptr = ip2rObj->HeaderPtr[m+1];
break;
}
l = m + 1;
}
}
//not matched just stop it
if ( sptr == 0 ) return 0;
indexBlockLen = eptr - sptr;
fseek(ip2rObj->dbHandler, sptr, 0);
if ( fread(buffer, indexBlockLen + INDEX_BLOCK_LENGTH, 1, ip2rObj->dbHandler) != 1 ) {
return 0;
}
dptr = 0; l = 0; h = indexBlockLen / INDEX_BLOCK_LENGTH;
while ( l <= h ) {
m = ((l + h) >> 1);
p = m * INDEX_BLOCK_LENGTH;
sip = getUnsignedInt(buffer, p);
if ( ip < sip ) {
h = m - 1;
} else {
eip = getUnsignedInt(buffer, p + 4);
if ( ip > eip ) {
l = m + 1;
} else {
dptr = getUnsignedInt(buffer, p + 8);
break;
}
}
}
if ( dptr == 0 ) return 0;
dataLen = ((dptr >> 24) & 0xFF);
dataptr = (dptr & 0x00FFFFFF);
fseek(ip2rObj->dbHandler, dataptr, 0);
if ( fread(buffer, dataLen, 1, ip2rObj->dbHandler) != 1 ) {
return 0;
}
datablock->city_id = getUnsignedInt(buffer, 0);
dataLen -= 4;
memcpy(datablock->region, buffer + 4, dataLen);
datablock->region[dataLen] = '\0';
return 1;
}
IP2R_API uint_t ip2region_btree_search_string(ip2region_t ip2rObj, const char *ip, datablock_t datablock)
{
return ip2region_btree_search(ip2rObj, ip2long(ip), datablock);
}
/**
* get a unsinged long(4bytes) from a specifield buffer start from the specifield offset
*
* @param buffer
* @param offset
* @return uint_t
*/
IP2R_API uint_t getUnsignedInt(const char *buffer, int offset)
{
return (
((buffer[offset ]) & 0x000000FF) |
((buffer[offset+1] << 8) & 0x0000FF00) |
((buffer[offset+2] << 16) & 0x00FF0000) |
((buffer[offset+3] << 24) & 0xFF000000)
);
}
/**
* string ip to long
*
* @param ip
* @return uint_t
*/
IP2R_API uint_t ip2long(const char *ip)
{
int i = 0, p = 24;
char buffer[4];
const char *cs = ip;
uint_t ipval = 0;
while ( *cs != '\0' ) {
if ( *cs == ' ' ) {
cs++;
continue;
}
if ( i > 3 ) {
ipval = 0;
break;
}
if ( *cs == '.' ) {
//single part length limit
if ( p < 0 ) break;
buffer[i] = '\0';
ipval |= (atoi(buffer) << p);
p -= 8;
i = 0;
} else {
buffer[i++] = *cs;
}
cs++;
}
//append the rest parts
if ( i > 3 ) return 0;
buffer[i] = '\0';
ipval |= atoi(buffer);
return ipval;
}
/**
* long to string ip
*
* @param ip
* @param buffer
* @return uint_t(1 for success and 0 for failed)
*/
IP2R_API uint_t long2ip(uint_t ip, char *buffer)
{
return 0;
}

View File

@ -1,152 +0,0 @@
/**
* ip2region header file
*
* @author chenxin<chenxin619315@gmail.com>
*/
#ifndef _IP2REGION_H
#define _IP2REGION_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//yat, just take it as this way, 99 percent and they works find
#if ( defined(_WIN32) || defined(_WINDOWS_) || defined(__WINDOWS_) )
# define OS_WINDOW
#else
# define OS_LINUX
#endif
#ifdef OS_WINDOW
# define IP2R_API extern __declspec(dllexport)
#else
/*platform shared library statement :: unix*/
# define IP2R_API extern
#endif
#define print(str) printf("%s", str)
#define println(str) printf("%s\n", str)
/*
* memory allocation macro definition.
* cause we should use emalloc,ecalloc .ege. in php.
* so you could make it better apdat the php environment.
*/
#define IP2R_CALLOC(_bytes, _blocks) calloc(_bytes, _blocks)
#define IP2R_MALLOC(_bytes) malloc(_bytes)
#define IP2R_FREE(_ptr) free(_ptr)
typedef unsigned short ushort_t;
typedef unsigned char uchar_t;
typedef unsigned int uint_t;
typedef unsigned long ulong_t;
#define INDEX_BLOCK_LENGTH 12
//thats 8 * 1024
#define TOTAL_HEADER_LENGTH 8192
/*
* ip2region properties struct
*/
typedef struct {
uint_t *HeaderSip; //header start ip blocks
uint_t *HeaderPtr; //header ptr blocks
uint_t headerLen; //header block number
char *dbFile; //path of db file
FILE *dbHandler; //file handler
char *dbBinStr; //db binary string for memory search mode
uint_t firstIndexPtr; //first index ptr
uint_t lastIndexPtr; //last index ptr
uint_t totalBlocks; //total index blocks number
} ip2region_entry;
typedef ip2region_entry * ip2region_t;
/*
* data block
*/
typedef struct {
uint_t city_id;
char region[256];
} datablock_entry;
typedef datablock_entry * datablock_t;
/**
* create a new ip2region object
*
* @param ip2rObj
* @param dbFile path
*/
IP2R_API uint_t ip2region_create(ip2region_t, const char *);
/**
* destroy the specified ip2region object
*
* @param ip2region_t
*/
IP2R_API uint_t ip2region_destroy(ip2region_t);
/**
* get the region associated with the specified ip address with the memory binary search algorithm
*
* @param ip2region_t
* @param uint_t
* @param datablock_t
* @date 2016/06/30
*/
IP2R_API uint_t ip2region_memory_search(ip2region_t, uint_t, datablock_t);
IP2R_API uint_t ip2region_memory_search_string(ip2region_t, const char *, datablock_t);
/**
* get the region associated with the specified ip address with binary search algorithm
*
* @param ip2rObj
* @param ip
* @param datablock
* @return uint_t
*/
IP2R_API uint_t ip2region_binary_search(ip2region_t, uint_t, datablock_t);
IP2R_API uint_t ip2region_binary_search_string(ip2region_t, const char *, datablock_t);
/**
* get the region associated with the specified ip address with b-tree algorithm
*
* @param ip2rObj
* @param ip
* @param datablock
* @return uint_t
*/
IP2R_API uint_t ip2region_btree_search(ip2region_t, uint_t, datablock_t);
IP2R_API uint_t ip2region_btree_search_string(ip2region_t, const char *, datablock_t);
/**
* get a unsinged long(4bytes) from a specified buffer start from the specified offset
*
* @param buffer
* @param offset
* @return uint_t
*/
IP2R_API uint_t getUnsignedInt(const char *, int);
/**
* string ip to long
*
* @param ip
* @return uint_t
*/
IP2R_API uint_t ip2long(const char *);
/**
* long to string ip
*
* @param ip
* @param buffer
* @return uint_t(1 for success and 0 for failed)
*/
IP2R_API uint_t long2ip(uint_t, char *);
#endif /*end ifndef*/

View File

@ -1,102 +0,0 @@
/**
* test ip2region searcher program
*
* @author chenxin<chenxin619315@gmail.com>
* @date 2015-10-30
*/
#include "ip2region.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#define __PRINT_ABOUT__ \
println("+-------------------------------------+"); \
println("| ip2region test program |"); \
println("| Author: chenxin619315@gmail.com. |"); \
println("| Type 'quit' to exit the program. |"); \
println("+-------------------------------------+");
//read a line from a command line.
static char *getLine( FILE *fp, char *__dst )
{
register int c;
register char *cs;
cs = __dst;
while ( ( c = getc( fp ) ) != EOF ) {
if ( c == '\n' ) break;
*cs++ = c;
}
*cs = '\0';
return ( c == EOF && cs == __dst ) ? NULL : __dst;
}
static double getTime()
{
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
return (tv.tv_sec * 1000 + ((double)tv.tv_usec)/1000);
}
int main( int argc, char **argv )
{
ip2region_entry ip2rEntry;
datablock_entry datablock;
char *dbFile = NULL, *algorithm = NULL;
char line[256];
uint_t (*func_ptr)(ip2region_t, const char *, datablock_t);
double s_time, c_time;
memset(&datablock, 0x00, sizeof(datablock_entry));
if ( argc < 2 ) {
printf("Usage: a.out [ip2region db file path] [algorithm]\n");
return 0;
}
dbFile = argv[1];
algorithm = "B-tree";
func_ptr = ip2region_btree_search_string;
if ( argc >= 3 ) {
if ( strcmp(argv[2], "binary") == 0 ) {
algorithm = "Binary";
func_ptr = ip2region_binary_search_string;
} else if ( strcmp(argv[2], "memory") == 0 ) {
algorithm = "Memory";
func_ptr = ip2region_memory_search_string;
}
}
//create a new ip2rObj
printf("+--initializing %s ... \n", algorithm);
if ( ip2region_create(&ip2rEntry, dbFile) == 0 ) {
println("Error: Fail to create the ip2region object\n");
return 0;
}
__PRINT_ABOUT__;
while ( 1 ) {
print("ip2region>> ");
getLine( stdin, line );
if ( strlen(line) < 2 ) continue;
if ( strcasecmp( line, "quit" ) == 0 ) {
println("+--Bye!");
break;
}
s_time = getTime();
func_ptr(&ip2rEntry, line, &datablock);
c_time = getTime() - s_time;
printf("%d|%s in %.5f millseconds\n", datablock.city_id, datablock.region, c_time);
}
// destory the ip2rObj
ip2region_destroy(&ip2rEntry);
return 0;
}

View File

@ -1,328 +0,0 @@
/**
* ip2region implementation with mmap support created by Leo Ma
*
* @see #ip2region.h
* @author chenxin<chenxin619315@gmail.com>
* @author Leo Ma<http://git.oschina.net/begeekmyfriend>
* @date 2017/01/12
*/
#include "ip2region.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
/**
* create a new ip2region object
*
* @param dbFile path
*/
IP2R_API uint_t ip2region_create(ip2region_t ip2rObj, char *dbFile)
{
struct stat st;
memset(ip2rObj, 0x00, sizeof(ip2region_entry));
ip2rObj->dbFile = IP2R_MALLOC(1024);
strcpy(ip2rObj->dbFile, dbFile);
int fd = open(dbFile, O_RDONLY);
if ( fd < 0 ) {
//fprintf(stderr, "Fail to open the db file %s\n", ip2rObj->dbFile);
return 0;
}
if ( fstat(fd, &st) < 0 ) {
//fprintf(stderr, "Fail to stat the db file %s\n", ip2rObj->dbFile);
return 0;
}
ip2rObj->dbSize = st.st_size;
ip2rObj->dbBinStr = mmap(NULL, ip2rObj->dbSize, PROT_READ, MAP_PRIVATE, fd, 0);
if ( ip2rObj->dbBinStr == (void *) -1 ) {
//fprintf(stderr, "Fail to map the db file %s\n", ip2rObj->dbFile);
return 0;
}
// Close db file as soon as possible.
close(fd);
ip2rObj->headerLen = 0;
ip2rObj->HeaderSip = (uint_t *) IP2R_MALLOC(TOTAL_HEADER_LENGTH);
if ( ip2rObj->HeaderSip == NULL ) {
return 0;
}
ip2rObj->HeaderPtr = (uint_t *) IP2R_MALLOC(TOTAL_HEADER_LENGTH);
if ( ip2rObj->HeaderPtr == NULL ) {
IP2R_FREE(ip2rObj->HeaderSip);
return 0;
}
ip2rObj->firstIndexPtr = getUnsignedInt(ip2rObj->dbBinStr, 0);
ip2rObj->lastIndexPtr = getUnsignedInt(ip2rObj->dbBinStr, 4);
ip2rObj->totalBlocks = (ip2rObj->lastIndexPtr-ip2rObj->firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
return 1;
}
/**
* destroy the specifield ip2region object
*
* @param ip2region_t
*/
IP2R_API uint_t ip2region_destroy(ip2region_t ip2rObj)
{
IP2R_FREE(ip2rObj->dbFile);
IP2R_FREE(ip2rObj->HeaderSip);
IP2R_FREE(ip2rObj->HeaderPtr);
//free the db binary string
if ( ip2rObj->dbBinStr != NULL ) {
munmap(ip2rObj->dbBinStr, ip2rObj->dbSize);
}
memset(ip2rObj, 0x00, sizeof(ip2region_entry));
return 1;
}
/**
* get the region associated with the specified ip address with the memory binary search algorithm
*
* @param ip2rObj
* @param ip
* @param datablock
*/
IP2R_API uint_t ip2region_binary_search(ip2region_t ip2rObj, uint_t ip, datablock_t datablock)
{
int l, h, m, p;
uint_t sip, eip, dptr;
int dataLen, dataptr;
char *buffer;
l = 0; h = ip2rObj->totalBlocks; dptr = 0;
while ( l <= h ) {
m = (l + h) >> 1;
p = ip2rObj->firstIndexPtr + m * INDEX_BLOCK_LENGTH;
buffer = ip2rObj->dbBinStr + p;
sip = getUnsignedInt(buffer, 0);
if ( ip < sip ) {
h = m - 1;
} else {
eip = getUnsignedInt(buffer, 4);
if ( ip > eip ) {
l = m + 1;
} else {
dptr = getUnsignedInt(buffer, 8);
break;
}
}
}
if ( dptr == 0 ) return 0;
//get the data
dataLen = ((dptr >> 24) & 0xFF);
dataptr = (dptr & 0x00FFFFFF);
buffer = ip2rObj->dbBinStr + dataptr;
//fill the data to the datablock
datablock->city_id = getUnsignedInt(buffer, 0);
dataLen -= 4; //reduce the length of the city_id
memcpy(datablock->region, buffer + 4, dataLen);
datablock->region[dataLen] = '\0';
return 1;
}
IP2R_API uint_t ip2region_binary_search_string(ip2region_t ip2rObj, char *ip, datablock_t datablock)
{
return ip2region_binary_search(ip2rObj, ip2long(ip), datablock);
}
/**
* get the region associated with the specifield ip address with b-tree algorithm
*
* @param ip2rObj
* @param ip
* @param datablock
* @return uint_t
*/
IP2R_API uint_t ip2region_btree_search(ip2region_t ip2rObj, uint_t ip, datablock_t datablock)
{
int i, j;
int l, m, h, p, sptr, eptr, indexBlockLen, dataLen, dataptr;
uint_t sip, eip, idxptr, dptr;
char *buffer;
if ( ip2rObj->headerLen == 0 ) {
buffer = ip2rObj->dbBinStr + 8;
for ( i = j = 0; i < TOTAL_HEADER_LENGTH; i += 8, j++ ) {
sip = getUnsignedInt(buffer, i);
idxptr = getUnsignedInt(buffer, i + 4);
if ( idxptr == 0 ) break;
ip2rObj->HeaderSip[j] = sip;
ip2rObj->HeaderPtr[j] = idxptr;
}
ip2rObj->headerLen = j;
}
//search the header block to define the index block
l = 0; h = ip2rObj->headerLen; sptr = 0; eptr = 0;
while ( l <= h ) {
m = ((l + h) >> 1);
//perfetc matched, just return it
if ( ip == ip2rObj->HeaderSip[m] ) {
if ( m > 0 ) {
sptr = ip2rObj->HeaderPtr[m-1];
eptr = ip2rObj->HeaderPtr[m ];
} else {
sptr = ip2rObj->HeaderPtr[m ];
eptr = ip2rObj->HeaderPtr[m+1];
}
break;
}
//less then the middle value
if ( ip < ip2rObj->HeaderSip[m] ) {
if ( m == 0 ) {
sptr = ip2rObj->HeaderPtr[m ];
eptr = ip2rObj->HeaderPtr[m+1];
break;
} else if ( ip > ip2rObj->HeaderSip[m-1] ) {
sptr = ip2rObj->HeaderPtr[m-1];
eptr = ip2rObj->HeaderPtr[m ];
break;
}
h = m - 1;
} else {
if ( m == ip2rObj->headerLen - 1 ) {
sptr = ip2rObj->HeaderPtr[m-1];
eptr = ip2rObj->HeaderPtr[m ];
break;
} else if ( ip <= ip2rObj->HeaderSip[m+1] ) {
sptr = ip2rObj->HeaderPtr[m ];
eptr = ip2rObj->HeaderPtr[m+1];
break;
}
l = m + 1;
}
}
//not matched just stop it
if ( sptr == 0 ) return 0;
indexBlockLen = eptr - sptr;
buffer = ip2rObj->dbBinStr + sptr;
dptr = 0; l = 0; h = indexBlockLen / INDEX_BLOCK_LENGTH;
while ( l <= h ) {
m = ((l + h) >> 1);
p = m * INDEX_BLOCK_LENGTH;
sip = getUnsignedInt(buffer, p);
if ( ip < sip ) {
h = m - 1;
} else {
eip = getUnsignedInt(buffer, p + 4);
if ( ip > eip ) {
l = m + 1;
} else {
dptr = getUnsignedInt(buffer, p + 8);
break;
}
}
}
if ( dptr == 0 ) return 0;
dataLen = ((dptr >> 24) & 0xFF);
dataptr = (dptr & 0x00FFFFFF);
buffer = ip2rObj->dbBinStr + dataptr;
datablock->city_id = getUnsignedInt(buffer, 0);
dataLen -= 4;
memcpy(datablock->region, buffer + 4, dataLen);
datablock->region[dataLen] = '\0';
return 1;
}
IP2R_API uint_t ip2region_btree_search_string(ip2region_t ip2rObj, char *ip, datablock_t datablock)
{
return ip2region_btree_search(ip2rObj, ip2long(ip), datablock);
}
/**
* get a unsinged long(4bytes) from a specifield buffer start from the specifield offset
*
* @param buffer
* @param offset
* @return uint_t
*/
IP2R_API uint_t getUnsignedInt(char *buffer, int offset)
{
return (
((buffer[offset ]) & 0x000000FF) |
((buffer[offset+1] << 8) & 0x0000FF00) |
((buffer[offset+2] << 16) & 0x00FF0000) |
((buffer[offset+3] << 24) & 0xFF000000)
);
}
/**
* string ip to long
*
* @param ip
* @return uint_t
*/
IP2R_API uint_t ip2long(char *ip)
{
int i = 0, p = 24;
char buffer[4], *cs = ip;
uint_t ipval = 0;
while ( *cs != '\0' ) {
if ( *cs == '.' ) {
//single part length limit
if ( i > 3 ) {
ipval = 0;
break;
}
if ( p < 0 ) break;
buffer[i] = '\0';
ipval |= (atoi(buffer) << p);
p -= 8;
i = 0;
} else {
buffer[i++] = *cs;
}
cs++;
}
//append the rest parts
if ( i > 3 ) return 0;
buffer[i] = '\0';
ipval |= atoi(buffer);
return ipval;
}
/**
* long to string ip
*
* @param ip
* @param buffer
* @return uint_t(1 for success and 0 for failed)
*/
IP2R_API uint_t long2ip(uint_t ip, char *buffer)
{
return 0;
}

View File

@ -1,138 +0,0 @@
/**
* ip2region header file
*
* @author chenxin<chenxin619315@gmail.com>
* @author Leo Ma<http://git.oschina.net/begeekmyfriend>
*/
#ifndef _IP2REGION_H
#define _IP2REGION_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//yat, just take it as this way, 99 percent and they works find
#if ( defined(_WIN32) || defined(_WINDOWS_) || defined(__WINDOWS_) )
# define OS_WINDOW
#else
# define OS_LINUX
#endif
#ifdef OS_WINDOW
# define IP2R_API extern __declspec(dllexport)
#else
/*platform shared library statement :: unix*/
# define IP2R_API extern
#endif
#define print(str) printf("%s", str)
#define println(str) printf("%s\n", str)
/*
* memory allocation macro definition.
* cause we should use emalloc,ecalloc .ege. in php.
* so you could make it better apdat the php environment.
*/
#define IP2R_CALLOC(_bytes, _blocks) calloc(_bytes, _blocks)
#define IP2R_MALLOC(_bytes) malloc(_bytes)
#define IP2R_FREE(_ptr) free(_ptr)
typedef unsigned short ushort_t;
typedef unsigned char uchar_t;
typedef unsigned int uint_t;
typedef unsigned long ulong_t;
#define INDEX_BLOCK_LENGTH 12
#define TOTAL_HEADER_LENGTH 8192
/*
* ip2region properties struct
*/
typedef struct {
uint_t *HeaderSip; //header start ip blocks
uint_t *HeaderPtr; //header ptr blocks
uint_t headerLen; //header block number
char *dbFile; //path of db file
char *dbBinStr; //db binary string for memory search mode
uint_t dbSize;
uint_t firstIndexPtr; //first index ptr
uint_t lastIndexPtr; //last index ptr
uint_t totalBlocks; //total index blocks number
} ip2region_entry;
typedef ip2region_entry * ip2region_t;
/*
* data block
*/
typedef struct {
uint_t city_id;
char region[256];
} datablock_entry;
typedef datablock_entry * datablock_t;
/**
* create a new ip2region object
*
* @param ip2rObj
* @param dbFile path
*/
IP2R_API uint_t ip2region_create(ip2region_t, char *);
/**
* destroy the specified ip2region object
*
* @param ip2region_t
*/
IP2R_API uint_t ip2region_destroy(ip2region_t);
/**
* get the region associated with the specified ip address with memory binary search algorithm
*
* @param ip2region_t
* @param uint_t
* @param datablock_t
* @date 2016/06/30
*/
IP2R_API uint_t ip2region_binary_search(ip2region_t, uint_t, datablock_t);
IP2R_API uint_t ip2region_binary_search_string(ip2region_t, char *, datablock_t);
/**
* get the region associated with the specified ip address with b-tree algorithm
*
* @param ip2rObj
* @param ip
* @param datablock
* @return uint_t
*/
IP2R_API uint_t ip2region_btree_search(ip2region_t, uint_t, datablock_t);
IP2R_API uint_t ip2region_btree_search_string(ip2region_t, char *, datablock_t);
/**
* get a unsinged long(4bytes) from a specified buffer start from the specified offset
*
* @param buffer
* @param offset
* @return uint_t
*/
IP2R_API uint_t getUnsignedInt(char *, int);
/**
* string ip to long
*
* @param ip
* @return uint_t
*/
IP2R_API uint_t ip2long(char *);
/**
* long to string ip
*
* @param ip
* @param buffer
* @return uint_t(1 for success and 0 for failed)
*/
IP2R_API uint_t long2ip(uint_t, char *);
#endif /*end ifndef*/

View File

@ -1,99 +0,0 @@
/**
* test ip2region searcher program
*
* @author chenxin<chenxin619315@gmail.com>
* @date 2015-10-30
*/
#include "ip2region.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#define __PRINT_ABOUT__ \
println("+-------------------------------------+"); \
println("| ip2region test program |"); \
println("| Author: chenxin619315@gmail.com. |"); \
println("| Type 'quit' to exit the program. |"); \
println("+-------------------------------------+");
//read a line from a command line.
static char *getLine( FILE *fp, char *__dst )
{
register int c;
register char *cs;
cs = __dst;
while ( ( c = getc( fp ) ) != EOF ) {
if ( c == '\n' ) break;
*cs++ = c;
}
*cs = '\0';
return ( c == EOF && cs == __dst ) ? NULL : __dst;
}
static double getTime()
{
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
return (tv.tv_sec * 1000 + ((double)tv.tv_usec)/1000);
}
int main( int argc, char **argv )
{
ip2region_entry ip2rEntry;
datablock_entry datablock;
char *dbFile = NULL, *algorithm = NULL;
char line[256];
uint_t (*func_ptr)(ip2region_t, char *, datablock_t);
double s_time, c_time;
memset(&datablock, 0x00, sizeof(datablock_entry));
if ( argc < 2 ) {
printf("Usage: a.out [ip2region db file path] [algorithm]\n");
return 0;
}
dbFile = argv[1];
algorithm = "B-tree";
func_ptr = ip2region_btree_search_string;
if ( argc >= 3 ) {
if ( strcmp(argv[2], "binary") == 0 ) {
algorithm = "File";
func_ptr = ip2region_binary_search_string;
}
}
//create a new ip2rObj
printf("+--initializing %s ... \n", algorithm);
if ( ip2region_create(&ip2rEntry, dbFile) == 0 ) {
println("Error: Fail to create the ip2region object\n");
return 0;
}
__PRINT_ABOUT__;
while ( 1 ) {
print("ip2region>> ");
getLine( stdin, line );
if ( strlen(line) < 2 ) continue;
if ( strcasecmp( line, "quit" ) == 0 ) {
println("+--Bye!");
break;
}
s_time = getTime();
func_ptr(&ip2rEntry, line, &datablock);
c_time = getTime() - s_time;
printf("%d|%s in %.5f millseconds\n", datablock.city_id, datablock.region, c_time);
}
//destory the ip2rObj
ip2region_destroy(&ip2rEntry);
return 0;
}

View File

@ -1,89 +0,0 @@
### golang 实现ip地址查询
#### 获取
```
go get github.com/lionsoul2014/ip2region/binding/golang
```
#### 使用
```golang
package main
import (
"fmt"
"github.com/lionsoul2014/ip2region/binding/golang/ip2region"
)
func main() {
fmt.Println("err")
region, err := ip2region.New("ip2region.db")
defer region.Close()
if err != nil {
fmt.Println(err)
return
}
ip, err := region.MemorySearch("127.0.0.1")
fmt.Println(ip, err)
ip, err = region.BinarySearch("127.0.0.1")
fmt.Println(ip, err)
ip, err = region.BtreeSearch("127.0.0.1")
fmt.Println(ip, err)
}
```
#### 返回对象
```golang
type IpInfo struct {
CityId int64
Country string
Region string
Province string
City string
ISP string
}
```
#### 性能
|名称|次数|平均耗时|
|---|---|------|
BenchmarkBtreeSearch-4| 200000 | 7715 ns/op
BenchmarkMemorySearch-4| 2000000 | 840 ns/op
BenchmarkBinarySearch-4| 30000 | 42680 ns/op
#### 测试程序
```
cd /binging/golang
go run main.go ../../data/ip2region.db
Or
go build -o ip2region main.go
./ip2region ../../data/ip2region.db
```
会看到如下界面
```
initializing
+-------------------------------------------------------+
| ip2region test script |
| format 'ip type' |
| type option 'b-tree','binary','memory' default b-tree |
| Type 'quit' to exit program |
+-------------------------------------------------------+
ip2reginon >> 127.0.0.1 memory
0|未分配或者内网IP|0|0|0|0 960.5µs
```

View File

@ -1,349 +0,0 @@
package ip2region
import (
"os"
"strings"
"strconv"
"io/ioutil"
"errors"
)
const (
INDEX_BLOCK_LENGTH = 12
TOTAL_HEADER_LENGTH = 8192
)
var err error
var ipInfo IpInfo
type Ip2Region struct {
// db file handler
dbFileHandler *os.File
//header block info
headerSip []int64
headerPtr []int64
headerLen int64
// super block index info
firstIndexPtr int64
lastIndexPtr int64
totalBlocks int64
// for memory mode only
// the original db binary string
dbBinStr []byte
dbFile string
}
type IpInfo struct {
CityId int64
Country string
Region string
Province string
City string
ISP string
}
func (ip IpInfo)String() string {
return strconv.FormatInt(ip.CityId, 10) + "|" + ip.Country + "|" + ip.Region + "|" + ip.Province + "|" + ip.City + "|" + ip.ISP
}
func getIpInfo(cityId int64, line []byte) IpInfo {
lineSlice := strings.Split(string(line), "|")
ipInfo := IpInfo{}
length := len(lineSlice)
ipInfo.CityId = cityId
if length < 5 {
for i := 0; i <= 5 - length; i++ {
lineSlice = append(lineSlice, "")
}
}
ipInfo.Country = lineSlice[0]
ipInfo.Region = lineSlice[1]
ipInfo.Province = lineSlice[2]
ipInfo.City = lineSlice[3]
ipInfo.ISP = lineSlice[4]
return ipInfo
}
func New(path string) (*Ip2Region, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
return &Ip2Region{
dbFile:path,
dbFileHandler:file,
}, nil
}
func (this *Ip2Region) Close() {
this.dbFileHandler.Close()
}
func (this *Ip2Region) MemorySearch(ipStr string) (ipInfo IpInfo, err error) {
ipInfo = IpInfo{}
if this.totalBlocks == 0 {
this.dbBinStr, err = ioutil.ReadFile(this.dbFile)
if err != nil {
return ipInfo, err
}
this.firstIndexPtr = getLong(this.dbBinStr, 0)
this.lastIndexPtr = getLong(this.dbBinStr, 4)
this.totalBlocks = (this.lastIndexPtr - this.firstIndexPtr) / INDEX_BLOCK_LENGTH + 1
}
ip, err := ip2long(ipStr)
if err != nil {
return ipInfo, err
}
h := this.totalBlocks
var dataPtr, l int64;
for (l <= h) {
m := (l + h) >> 1
p := this.firstIndexPtr + m * INDEX_BLOCK_LENGTH
sip := getLong(this.dbBinStr, p)
if ip < sip {
h = m - 1
} else {
eip := getLong(this.dbBinStr, p + 4)
if ip > eip {
l = m + 1
} else {
dataPtr = getLong(this.dbBinStr, p + 8)
break;
}
}
}
if dataPtr == 0 {
return ipInfo, errors.New("not found")
}
dataLen := ((dataPtr >> 24) & 0xFF)
dataPtr = (dataPtr & 0x00FFFFFF);
ipInfo = getIpInfo(getLong(this.dbBinStr, dataPtr), this.dbBinStr[(dataPtr) + 4:dataPtr + dataLen])
return ipInfo, nil
}
func (this *Ip2Region)BinarySearch(ipStr string) (ipInfo IpInfo, err error) {
ipInfo = IpInfo{}
if this.totalBlocks == 0 {
this.dbFileHandler.Seek(0, 0)
superBlock := make([]byte, 8)
this.dbFileHandler.Read(superBlock)
this.firstIndexPtr = getLong(superBlock, 0)
this.lastIndexPtr = getLong(superBlock, 4)
this.totalBlocks = (this.lastIndexPtr - this.firstIndexPtr) / INDEX_BLOCK_LENGTH + 1
}
var l, dataPtr, p int64
h := this.totalBlocks
ip, err := ip2long(ipStr)
if err != nil {
return
}
for (l <= h) {
m := (l + h) >> 1
p = m * INDEX_BLOCK_LENGTH
_, err = this.dbFileHandler.Seek(this.firstIndexPtr + p, 0)
if err != nil {
return
}
buffer := make([]byte, INDEX_BLOCK_LENGTH)
_, err = this.dbFileHandler.Read(buffer)
if err != nil {
}
sip := getLong(buffer, 0)
if ip < sip {
h = m - 1
} else {
eip := getLong(buffer, 4)
if ip > eip {
l = m + 1
} else {
dataPtr = getLong(buffer, 8)
break;
}
}
}
if dataPtr == 0 {
err = errors.New("not found")
return
}
dataLen := ((dataPtr >> 24) & 0xFF)
dataPtr = (dataPtr & 0x00FFFFFF);
this.dbFileHandler.Seek(dataPtr, 0)
data := make([]byte, dataLen)
this.dbFileHandler.Read(data)
ipInfo = getIpInfo(getLong(data, 0), data[4:dataLen])
err = nil
return
}
func (this *Ip2Region) BtreeSearch(ipStr string) (ipInfo IpInfo, err error) {
ipInfo = IpInfo{}
ip, err := ip2long(ipStr)
if this.headerLen == 0 {
this.dbFileHandler.Seek(8, 0)
buffer := make([]byte, TOTAL_HEADER_LENGTH)
this.dbFileHandler.Read(buffer)
var idx int64;
for i := 0; i < TOTAL_HEADER_LENGTH; i += 8 {
startIp := getLong(buffer, int64(i))
dataPar := getLong(buffer, int64(i + 4))
if dataPar == 0 {
break
}
this.headerSip = append(this.headerSip, startIp)
this.headerPtr = append(this.headerPtr, dataPar)
idx ++;
}
this.headerLen = idx
}
var l, sptr, eptr int64
h := this.headerLen
for l <= h {
m := int64(l + h) >> 1
if m < this.headerLen {
if ip == this.headerSip[m] {
if m > 0 {
sptr = this.headerPtr[m - 1]
eptr = this.headerPtr[m]
} else {
sptr = this.headerPtr[m]
eptr = this.headerPtr[m + 1]
}
break
}
if ip < this.headerSip[m] {
if m == 0 {
sptr = this.headerPtr[m]
eptr = this.headerPtr[m + 1]
break
} else if ip > this.headerSip[m - 1] {
sptr = this.headerPtr[m - 1]
eptr = this.headerPtr[m]
break
}
h = m - 1
} else {
if m == this.headerLen - 1 {
sptr = this.headerPtr[m - 1]
eptr = this.headerPtr[m]
break
} else if ip <= this.headerSip[m + 1] {
sptr = this.headerPtr[m ]
eptr = this.headerPtr[m + 1]
break
}
l = m + 1
}
}
}
if sptr == 0 {
err = errors.New("not found")
return
}
blockLen := eptr - sptr
this.dbFileHandler.Seek(sptr, 0)
index := make([]byte, blockLen + INDEX_BLOCK_LENGTH)
this.dbFileHandler.Read(index)
var dataptr int64
h = blockLen / INDEX_BLOCK_LENGTH
l = 0
for l <= h {
m := int64(l + h) >> 1
p := m * INDEX_BLOCK_LENGTH
sip := getLong(index, p)
if ip < sip {
h = m - 1;
} else {
eip := getLong(index, p + 4)
if ip > eip {
l = m + 1
} else {
dataptr = getLong(index, p + 8)
break
}
}
}
if dataptr == 0 {
err = errors.New("not found")
return
}
dataLen := (dataptr >> 24) & 0xFF
dataPtr := dataptr & 0x00FFFFFF
this.dbFileHandler.Seek(dataPtr, 0)
data := make([]byte, dataLen)
this.dbFileHandler.Read(data)
ipInfo = getIpInfo(getLong(data, 0), data[4:])
return
}
func getLong(b []byte, offset int64) int64 {
val := (int64(b[offset ]) |
int64(b[offset + 1]) << 8 |
int64(b[offset + 2]) << 16 |
int64(b[offset + 3]) << 24)
return val
}
func ip2long(IpStr string) (int64, error) {
bits := strings.Split(IpStr, ".")
if len(bits) != 4 {
return 0, errors.New("ip format error")
}
var sum int64
for i, n := range bits {
bit, _ := strconv.ParseInt(n, 10, 64)
sum += bit << uint(24 - 8 * i)
}
return sum, nil
}

View File

@ -1,49 +0,0 @@
package ip2region
import (
"testing"
)
func BenchmarkBtreeSearch(B *testing.B) {
region, err := New("../../data/ip2region.db ")
if err != nil {
B.Error(err)
}
for i:=0;i<B.N;i++{
region.BtreeSearch("127.0.0.1")
}
}
func BenchmarkMemorySearch(B *testing.B) {
region, err := New("../../data/ip2region.db ")
if err != nil {
B.Error(err)
}
for i:=0;i<B.N;i++{
region.MemorySearch("127.0.0.1")
}
}
func BenchmarkBinarySearch(B *testing.B) {
region, err := New("../../data/ip2region.db ")
if err != nil {
B.Error(err)
}
for i:=0;i<B.N;i++{
region.BinarySearch("127.0.0.1")
}
}
func TestIp2long(t *testing.T) {
ip, err := ip2long("127.0.0.1")
if err != nil {
t.Error(err)
}
if ip != 2130706433 {
t.Error("result error")
}
t.Log(ip)
}

View File

@ -1,70 +0,0 @@
package main
import (
"os"
"github.com/lionsoul2014/ip2region/binding/golang/ip2region"
"bufio"
"fmt"
"strings"
"errors"
"time"
)
func main() {
db := os.Args[1]
_,err:= os.Stat(db)
if os.IsNotExist(err){
panic("not found db " + db)
}
region, err := ip2region.New(db)
defer region.Close()
fmt.Println(`initializing
+-------------------------------------------------------+
| ip2region test script |
| format 'ip type' |
| type option 'b-tree','binary','memory' default b-tree |
| Type 'quit' to exit program |
+-------------------------------------------------------+`)
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("ip2reginon >> ")
data, _, _ := reader.ReadLine()
begin:= time.Now()
commands := strings.Fields(string(data))
ip := ip2region.IpInfo{}
len := len(commands)
if len == 0{
continue
}
if commands[0] == "quit"{
break
}
if !(len > 1) {
commands = append(commands, "b-tree")
}
switch commands[1] {
case "b-tree":
ip, err = region.BtreeSearch(commands[0])
case "binary":
ip, err = region.BinarySearch(commands[0])
case "memory":
ip, err = region.MemorySearch(commands[0])
default:
err = errors.New("parameter error")
}
if err != nil {
fmt.Println( fmt.Sprintf("\x1b[0;31m%s\x1b[0m",err.Error()))
}else{
fmt.Println( fmt.Sprintf("\x1b[0;32m%s %s\x1b[0m",ip.String(),time.Since(begin).String()))
}
}
}

View File

@ -1,72 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="ip2region" default="usage" basedir=".">
<!--Initialize-->
<target name="init">
<echo message="------------------------------------------------------------"/>
<echo message="----------BUILDING JCSEG PACKAGE----------------------------"/>
<echo message=""/>
<property name="bottom" value="ip2region 2015"/>
<property name="jars" value="${basedir}"/>
<property name="sources" value="${basedir}/src"/>
<property name="classes" value="${basedir}/classes"/>
<property name="version" value="1.4"/>
<property name="api" value="${basedir}/doc"/>
<mkdir dir="${classes}"/>
<mkdir dir="${api}"/>
</target>
<path id="classpath">
<fileset dir="${lib.dir}" includes="**/*.jar"/>
</path>
<!--Build-->
<target name="build" depends="init">
<echo message="-------------Compiling Application--------------"/>
<javac srcdir="${sources}" destdir="${classes}"></javac>
</target>
<!--Archive-->
<target name="dist" depends="build">
<jar jarfile="${jars}/ip2region-${version}.jar" basedir="${classes}">
<!--class fileter-->
<include name="**/*"/>
<!--manifest information setting-->
<manifest>
<attribute name="Main-Class" value="org.lionsoul.ip2region.test.TestSearcher"/>
<attribute name="Class-Path" value=""/>
</manifest>
</jar>
</target>
<!--Java document-->
<target name="all" depends="dist">
<echo message="------------Making Java Document------------------"/>
<javadoc packagenames="org.*"
sourcepath="${sources}"
destdir="${api}"
bottom="${bottom}"
charset="UTF-8"
author="false">
<classpath>
<pathelement location="${classes}"/>
</classpath>
</javadoc>
<jar jarfile="${jars}/ip2region-${version}-javadoc.jar" basedir="${api}" includes="**/*"></jar>
<!--do the data clean up-->
<delete dir="${classes}"/>
<delete dir="${api}"/>
</target>
<target name="usage">
<echo message="*** ip2region ANT Build Script ***"/>
<echo message="Usage: "/>
<echo message=" ant [target]"/>
<echo message=""/>
<echo message=" target : "/>
<echo message=" build : Build Application"/>
<echo message=" dist : Build Application + Archive (JAR)"/>
<echo message=" all : Build Application + Archive + JavaDoc"/>
</target>
</project>

View File

@ -1,190 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7.2</version>
<packaging>jar</packaging>
<name>ip2region</name>
<url>http://gitee.com/lionsoul/ip2region/</url>
<description>Open source internel address locator</description>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<scm>
<url>git@gitee.com:lionsoul/ip2region.git</url>
<connection>scm:git:git@gitee.com:lionsoul/ip2region.git</connection>
<developerConnection>scm:git:git@gitee.com:lionsoul/ip2region.git</developerConnection>
</scm>
<developers>
<developer>
<id>lionsoul</id>
<name>chenxin</name>
<email>chenxin619315@gmail.com</email>
</developer>
</developers>
<issueManagement>
<url>http://gitee.com/lionsoul/ip2region/issues</url>
<system>gitee issues</system>
</issueManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>attach-javadocs</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<additionalparam>${javadoc.opts}</additionalparam>
</configuration>
</execution>
</executions>
<configuration>
<failOnError>false</failOnError>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.lionsoul.ip2region.test.TestSearcher</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>java8-doclint-disabled</id>
<activation>
<jdk>[1.8,)</jdk>
</activation>
<properties>
<javadoc.opts>-Xdoclint:none</javadoc.opts>
</properties>
</profile>
<profile>
<id>release</id>
<build>
<plugins>
<!-- Source -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Javadoc -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<additionalparam>${javadoc.opts}</additionalparam>
</configuration>
</execution>
</executions>
</plugin>
<!-- GPG -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<distributionManagement>
<snapshotRepository>
<id>oss-parent</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</snapshotRepository>
<repository>
<id>oss-parent</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
</profile>
</profiles>
</project>

View File

@ -1,86 +0,0 @@
package org.lionsoul.ip2region;
/**
* data block class
*
* @author chenxin<chenxin619315@gmail.com>
*/
public class DataBlock
{
/**
* city id
*/
private int city_id;
/**
* region address
*/
private String region;
/**
* region ptr in the db file
*/
private int dataPtr;
/**
* construct method
*
* @param city_id
* @param region region string
* @param ptr data ptr
*/
public DataBlock( int city_id, String region, int dataPtr )
{
this.city_id = city_id;
this.region = region;
this.dataPtr = dataPtr;
}
public DataBlock(int city_id, String region)
{
this(city_id, region, 0);
}
public int getCityId()
{
return city_id;
}
public DataBlock setCityId(int city_id)
{
this.city_id = city_id;
return this;
}
public String getRegion()
{
return region;
}
public DataBlock setRegion(String region)
{
this.region = region;
return this;
}
public int getDataPtr()
{
return dataPtr;
}
public DataBlock setDataPtr(int dataPtr)
{
this.dataPtr = dataPtr;
return this;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(city_id).append('|').append(region).append('|').append(dataPtr);
return sb.toString();
}
}

View File

@ -1,64 +0,0 @@
package org.lionsoul.ip2region;
/**
* database configuration class
*
* @author chenxin<chenxin619315@gmail.com>
*/
public class DbConfig
{
/**
* total header data block size
*/
private int totalHeaderSize;
/**
* max index data block size
* u should always choice the fastest read block size
*/
private int indexBlockSize;
/**
* construct method
*
* @param totalHeaderSize
* @param dataBlockSize
* @throws DbMakerConfigException
*/
public DbConfig( int totalHeaderSize ) throws DbMakerConfigException
{
if ( (totalHeaderSize % 8) != 0 ) {
throw new DbMakerConfigException("totalHeaderSize must be times of 8");
}
this.totalHeaderSize = totalHeaderSize;
this.indexBlockSize = 8192; //4 * 2048
}
public DbConfig() throws DbMakerConfigException
{
this(8 * 2048);
}
public int getTotalHeaderSize()
{
return totalHeaderSize;
}
public DbConfig setTotalHeaderSize(int totalHeaderSize)
{
this.totalHeaderSize = totalHeaderSize;
return this;
}
public int getIndexBlockSize()
{
return indexBlockSize;
}
public DbConfig setIndexBlockSize(int dataBlockSize)
{
this.indexBlockSize = dataBlockSize;
return this;
}
}

View File

@ -1,26 +0,0 @@
package org.lionsoul.ip2region;
/**
* configuration exception
*
* @author chenxin<chenxin619315@gmail.com>
*/
public class DbMakerConfigException extends Exception
{
private static final long serialVersionUID = 4495714680349884838L;
public DbMakerConfigException( String info )
{
super(info);
}
public DbMakerConfigException( Throwable res )
{
super(res);
}
public DbMakerConfigException( String info, Throwable res )
{
super(info, res);
}
}

View File

@ -1,409 +0,0 @@
package org.lionsoul.ip2region;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* ip db searcher class (Not thread safe)
*
* @author chenxin<chenxin619315@gmail.com>
*/
public class DbSearcher
{
public static final int BTREE_ALGORITHM = 1;
public static final int BINARY_ALGORITHM = 2;
public static final int MEMORY_ALGORITYM = 3;
/**
* db config
*/
private DbConfig dbConfig = null;
/**
* db file access handler
*/
private RandomAccessFile raf = null;
/**
* header blocks buffer
*/
private long[] HeaderSip = null;
private int[] HeaderPtr = null;
private int headerLength;
/**
* super blocks info
*/
private long firstIndexPtr = 0;
private long lastIndexPtr = 0;
private int totalIndexBlocks = 0;
/**
* for memory mode
* the original db binary string
*/
private byte[] dbBinStr = null;
/**
* construct class
*
* @param bdConfig
* @param dbFile
* @throws FileNotFoundException
*/
public DbSearcher( DbConfig dbConfig, String dbFile ) throws FileNotFoundException
{
this.dbConfig = dbConfig;
raf = new RandomAccessFile(dbFile, "r");
}
/**
* construct method with self-define std ip2region binary string support
* Thanks to the issue from Wendal at https://gitee.com/lionsoul/ip2region/issues/IILFL.
*
* Note: This construtor should be used for memory search ONLY !!!
*
* @param dbConfig
* @param dbBinStr
*/
public DbSearcher(DbConfig dbConfig, byte[] dbBinStr)
{
this.dbConfig = dbConfig;
this.dbBinStr = dbBinStr;
firstIndexPtr = Util.getIntLong(dbBinStr, 0);
lastIndexPtr = Util.getIntLong(dbBinStr, 4);
totalIndexBlocks = (int)((lastIndexPtr - firstIndexPtr)/IndexBlock.getIndexBlockLength()) + 1;
}
/**
* get the region with a int ip address with memory binary search algorithm
*
* @param ip
* @throws IOException
*/
public DataBlock memorySearch(long ip) throws IOException
{
int blen = IndexBlock.getIndexBlockLength();
if ( dbBinStr == null ) {
dbBinStr = new byte[(int)raf.length()];
raf.seek(0L);
raf.readFully(dbBinStr, 0, dbBinStr.length);
//initialize the global vars
firstIndexPtr = Util.getIntLong(dbBinStr, 0);
lastIndexPtr = Util.getIntLong(dbBinStr, 4);
totalIndexBlocks = (int)((lastIndexPtr - firstIndexPtr)/blen) + 1;
}
//search the index blocks to define the data
int l = 0, h = totalIndexBlocks;
long sip, eip, dataptr = 0;
while ( l <= h ) {
int m = (l + h) >> 1;
int p = (int)(firstIndexPtr + m * blen);
sip = Util.getIntLong(dbBinStr, p);
if ( ip < sip ) {
h = m - 1;
} else {
eip = Util.getIntLong(dbBinStr, p + 4);
if ( ip > eip ) {
l = m + 1;
} else {
dataptr = Util.getIntLong(dbBinStr, p + 8);
break;
}
}
}
//not matched
if ( dataptr == 0 ) return null;
//get the data
int dataLen = (int)((dataptr >> 24) & 0xFF);
int dataPtr = (int)((dataptr & 0x00FFFFFF));
int city_id = (int)Util.getIntLong(dbBinStr, dataPtr);
String region = new String(dbBinStr, dataPtr + 4, dataLen - 4, "UTF-8");
return new DataBlock(city_id, region, dataPtr);
}
/**
* get the region throught the ip address with memory binary search algorithm
*
* @param ip
* @return DataBlock
* @throws IOException
*/
public DataBlock memorySearch( String ip ) throws IOException
{
return memorySearch(Util.ip2long(ip));
}
/**
* get by index ptr
*
* @param indexPtr
* @throws IOException
*/
public DataBlock getByIndexPtr( long ptr ) throws IOException
{
raf.seek(ptr);
byte[] buffer = new byte[12];
raf.readFully(buffer, 0, buffer.length);
//long startIp = Util.getIntLong(buffer, 0);
//long endIp = Util.getIntLong(buffer, 4);
long extra = Util.getIntLong(buffer, 8);
int dataLen = (int)((extra >> 24) & 0xFF);
int dataPtr = (int)((extra & 0x00FFFFFF));
raf.seek(dataPtr);
byte[] data = new byte[dataLen];
raf.readFully(data, 0, data.length);
int city_id = (int)Util.getIntLong(data, 0);
String region = new String(data, 4, data.length - 4, "UTF-8");
return new DataBlock(city_id, region, dataPtr);
}
/**
* get the region with a int ip address with b-tree algorithm
*
* @param ip
* @throws IOException
*/
public DataBlock btreeSearch( long ip ) throws IOException
{
//check and load the header
if ( HeaderSip == null ) {
raf.seek(8L); //pass the super block
byte[] b = new byte[dbConfig.getTotalHeaderSize()];
// byte[] b = new byte[4096];
raf.readFully(b, 0, b.length);
//fill the header
int len = b.length >> 3, idx = 0; //b.lenght / 8
HeaderSip = new long[len];
HeaderPtr = new int [len];
long startIp, dataPtr;
for ( int i = 0; i < b.length; i += 8 ) {
startIp = Util.getIntLong(b, i);
dataPtr = Util.getIntLong(b, i + 4);
if ( dataPtr == 0 ) break;
HeaderSip[idx] = startIp;
HeaderPtr[idx] = (int)dataPtr;
idx++;
}
headerLength = idx;
}
//1. define the index block with the binary search
if ( ip == HeaderSip[0] ) {
return getByIndexPtr(HeaderPtr[0]);
} else if ( ip == HeaderSip[headerLength-1] ) {
return getByIndexPtr(HeaderPtr[headerLength-1]);
}
int l = 0, h = headerLength, sptr = 0, eptr = 0;
while ( l <= h ) {
int m = (l + h) >> 1;
//perfetc matched, just return it
if ( ip == HeaderSip[m] ) {
if ( m > 0 ) {
sptr = HeaderPtr[m-1];
eptr = HeaderPtr[m ];
} else {
sptr = HeaderPtr[m ];
eptr = HeaderPtr[m+1];
}
break;
}
//less then the middle value
if ( ip < HeaderSip[m] ) {
if ( m == 0 ) {
sptr = HeaderPtr[m ];
eptr = HeaderPtr[m+1];
break;
} else if ( ip > HeaderSip[m-1] ) {
sptr = HeaderPtr[m-1];
eptr = HeaderPtr[m ];
break;
}
h = m - 1;
} else {
if ( m == headerLength - 1 ) {
sptr = HeaderPtr[m-1];
eptr = HeaderPtr[m ];
break;
} else if ( ip <= HeaderSip[m+1] ) {
sptr = HeaderPtr[m ];
eptr = HeaderPtr[m+1];
break;
}
l = m + 1;
}
}
//match nothing just stop it
if ( sptr == 0 ) return null;
//2. search the index blocks to define the data
int blockLen = eptr - sptr, blen = IndexBlock.getIndexBlockLength();
byte[] iBuffer = new byte[blockLen + blen]; //include the right border block
raf.seek(sptr);
raf.readFully(iBuffer, 0, iBuffer.length);
l = 0; h = blockLen / blen;
long sip, eip, dataptr = 0;
while ( l <= h ) {
int m = (l + h) >> 1;
int p = m * blen;
sip = Util.getIntLong(iBuffer, p);
if ( ip < sip ) {
h = m - 1;
} else {
eip = Util.getIntLong(iBuffer, p + 4);
if ( ip > eip ) {
l = m + 1;
} else {
dataptr = Util.getIntLong(iBuffer, p + 8);
break;
}
}
}
//not matched
if ( dataptr == 0 ) return null;
//3. get the data
int dataLen = (int)((dataptr >> 24) & 0xFF);
int dataPtr = (int)((dataptr & 0x00FFFFFF));
raf.seek(dataPtr);
byte[] data = new byte[dataLen];
raf.readFully(data, 0, data.length);
int city_id = (int)Util.getIntLong(data, 0);
String region = new String(data, 4, data.length - 4, "UTF-8");
return new DataBlock(city_id, region, dataPtr);
}
/**
* get the region throught the ip address with b-tree search algorithm
*
* @param ip
* @return DataBlock
* @throws IOException
*/
public DataBlock btreeSearch( String ip ) throws IOException
{
return btreeSearch(Util.ip2long(ip));
}
/**
* get the region with a int ip address with binary search algorithm
*
* @param ip
* @throws IOException
*/
public DataBlock binarySearch( long ip ) throws IOException
{
int blen = IndexBlock.getIndexBlockLength();
if ( totalIndexBlocks == 0 ) {
raf.seek(0L);
byte[] superBytes = new byte[8];
raf.readFully(superBytes, 0, superBytes.length);
//initialize the global vars
firstIndexPtr = Util.getIntLong(superBytes, 0);
lastIndexPtr = Util.getIntLong(superBytes, 4);
totalIndexBlocks = (int)((lastIndexPtr - firstIndexPtr)/blen) + 1;
}
//search the index blocks to define the data
int l = 0, h = totalIndexBlocks;
byte[] buffer = new byte[blen];
long sip, eip, dataptr = 0;
while ( l <= h ) {
int m = (l + h) >> 1;
raf.seek(firstIndexPtr + m * blen); //set the file pointer
raf.readFully(buffer, 0, buffer.length);
sip = Util.getIntLong(buffer, 0);
if ( ip < sip ) {
h = m - 1;
} else {
eip = Util.getIntLong(buffer, 4);
if ( ip > eip ) {
l = m + 1;
} else {
dataptr = Util.getIntLong(buffer, 8);
break;
}
}
}
//not matched
if ( dataptr == 0 ) return null;
//get the data
int dataLen = (int)((dataptr >> 24) & 0xFF);
int dataPtr = (int)((dataptr & 0x00FFFFFF));
raf.seek(dataPtr);
byte[] data = new byte[dataLen];
raf.readFully(data, 0, data.length);
int city_id = (int)Util.getIntLong(data, 0);
String region = new String(data, 4, data.length - 4, "UTF-8");
return new DataBlock(city_id, region, dataPtr);
}
/**
* get the region throught the ip address with binary search algorithm
*
* @param ip
* @return DataBlock
* @throws IOException
*/
public DataBlock binarySearch( String ip ) throws IOException
{
return binarySearch(Util.ip2long(ip));
}
/**
* get the db config
*
* @return DbConfig
*/
public DbConfig getDbConfig()
{
return dbConfig;
}
/**
* close the db
*
* @throws IOException
*/
public void close() throws IOException
{
HeaderSip = null; //let gc do its work
HeaderPtr = null;
dbBinStr = null;
if ( raf != null ) {
raf.close();
}
}
}

View File

@ -1,68 +0,0 @@
package org.lionsoul.ip2region;
/**
* header block class
*
* @author chenxin<chenxin619315@gmail.com>
*/
public class HeaderBlock
{
/**
* index block start ip address
*/
private long indexStartIp;
/**
* ip address
*/
private int indexPtr;
public HeaderBlock( long indexStartIp, int indexPtr )
{
this.indexStartIp = indexStartIp;
this.indexPtr = indexPtr;
}
public long getIndexStartIp()
{
return indexStartIp;
}
public HeaderBlock setIndexStartIp(long indexStartIp)
{
this.indexStartIp = indexStartIp;
return this;
}
public int getIndexPtr()
{
return indexPtr;
}
public HeaderBlock setIndexPtr(int indexPtr)
{
this.indexPtr = indexPtr;
return this;
}
/**
* get the bytes for db storage
*
* @return byte[]
*/
public byte[] getBytes()
{
/*
* +------------+-----------+
* | 4bytes | 4bytes |
* +------------+-----------+
* start ip index ptr
*/
byte[] b = new byte[8];
Util.writeIntLong(b, 0, indexStartIp);
Util.writeIntLong(b, 4, indexPtr);
return b;
}
}

View File

@ -1,113 +0,0 @@
package org.lionsoul.ip2region;
/**
* item index class
*
* @author chenxin<chenxin619315@gmail.com>
*/
public class IndexBlock
{
private static int LENGTH = 12;
/**
* start ip address
*/
private long startIp;
/**
* end ip address
*/
private long endIp;
/**
* data ptr and data length
*/
private int dataPtr;
/**
* data length
*/
private int dataLen;
public IndexBlock(long startIp, long endIp, int dataPtr, int dataLen)
{
this.startIp = startIp;
this.endIp = endIp;
this.dataPtr = dataPtr;
this.dataLen = dataLen;
}
public long getStartIp()
{
return startIp;
}
public IndexBlock setStartIp(long startIp)
{
this.startIp = startIp;
return this;
}
public long getEndIp()
{
return endIp;
}
public IndexBlock setEndIp(long endIp)
{
this.endIp = endIp;
return this;
}
public int getDataPtr()
{
return dataPtr;
}
public IndexBlock setDataPtr(int dataPtr)
{
this.dataPtr = dataPtr;
return this;
}
public int getDataLen()
{
return dataLen;
}
public IndexBlock setDataLen(int dataLen)
{
this.dataLen = dataLen;
return this;
}
public static int getIndexBlockLength()
{
return LENGTH;
}
/**
* get the bytes for storage
*
* @return byte[]
*/
public byte[] getBytes()
{
/*
* +------------+-----------+-----------+
* | 4bytes | 4bytes | 4bytes |
* +------------+-----------+-----------+
* start ip end ip data ptr + len
*/
byte[] b = new byte[12];
Util.writeIntLong(b, 0, startIp); //start ip
Util.writeIntLong(b, 4, endIp); //end ip
//write the data ptr and the length
long mix = dataPtr | ((dataLen << 24) & 0xFF000000L);
Util.writeIntLong(b, 8, mix);
return b;
}
}

View File

@ -1,143 +0,0 @@
package org.lionsoul.ip2region;
/**
* util class
*
* @author chenxin<chenxin619315@gmail.com>
*/
public class Util
{
/**
* write specfield bytes to a byte array start from offset
*
* @param b
* @param offset
* @param v
* @param bytes
*/
public static void write( byte[] b, int offset, long v, int bytes)
{
for ( int i = 0; i < bytes; i++ ) {
b[offset++] = (byte)((v >>> (8 * i)) & 0xFF);
}
}
/**
* write a int to a byte array
*
* @param b
* @param offet
* @param v
*/
public static void writeIntLong( byte[] b, int offset, long v )
{
b[offset++] = (byte)((v >> 0) & 0xFF);
b[offset++] = (byte)((v >> 8) & 0xFF);
b[offset++] = (byte)((v >> 16) & 0xFF);
b[offset ] = (byte)((v >> 24) & 0xFF);
}
/**
* get a int from a byte array start from the specifiled offset
*
* @param b
* @param offset
*/
public static long getIntLong( byte[] b, int offset )
{
return (
((b[offset++] & 0x000000FFL)) |
((b[offset++] << 8) & 0x0000FF00L) |
((b[offset++] << 16) & 0x00FF0000L) |
((b[offset ] << 24) & 0xFF000000L)
);
}
/**
* get a int from a byte array start from the specifield offset
*
* @param b
* @param offset
*/
public static int getInt3( byte[] b, int offset )
{
return (
(b[offset++] & 0x000000FF) |
(b[offset++] & 0x0000FF00) |
(b[offset ] & 0x00FF0000)
);
}
public static int getInt2( byte[] b, int offset )
{
return (
(b[offset++] & 0x000000FF) |
(b[offset ] & 0x0000FF00)
);
}
public static int getInt1( byte[] b, int offset )
{
return (
(b[offset] & 0x000000FF)
);
}
/**
* string ip to long ip
*
* @param ip
* @return long
*/
public static long ip2long( String ip )
{
String[] p = ip.split("\\.");
if ( p.length != 4 ) return 0;
int p1 = ((Integer.valueOf(p[0]) << 24) & 0xFF000000);
int p2 = ((Integer.valueOf(p[1]) << 16) & 0x00FF0000);
int p3 = ((Integer.valueOf(p[2]) << 8) & 0x0000FF00);
int p4 = ((Integer.valueOf(p[3]) << 0) & 0x000000FF);
return ((p1 | p2 | p3 | p4) & 0xFFFFFFFFL);
}
/**
* int to ip string
*
* @param ip
* @return string
*/
public static String long2ip( long ip )
{
StringBuilder sb = new StringBuilder();
sb
.append((ip >> 24) & 0xFF).append('.')
.append((ip >> 16) & 0xFF).append('.')
.append((ip >> 8) & 0xFF).append('.')
.append((ip >> 0) & 0xFF);
return sb.toString();
}
/**
* check the validate of the specifeld ip address
*
* @param ip
* @return boolean
*/
public static boolean isIpAddress( String ip )
{
String[] p = ip.split("\\.");
if ( p.length != 4 ) return false;
for ( String pp : p ) {
if ( pp.length() > 3 ) return false;
int val = Integer.valueOf(pp);
if ( val > 255 ) return false;
}
return true;
}
}

View File

@ -1,120 +0,0 @@
package org.lionsoul.ip2region.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbMakerConfigException;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
/**
* project test script
*
* @author chenxin<chenxin619315@gmail.com>
*/
public class TestSearcher
{
public static void main(String[] argv)
{
if ( argv.length == 0 ) {
System.out.println("| Usage: java -jar ip2region-{version}.jar [ip2region db file]");
return;
}
File file = new File(argv[0]);
if ( file.exists() == false ) {
System.out.println("Error: Invalid ip2region.db file");
return;
}
int algorithm = DbSearcher.BTREE_ALGORITHM;
String algoName = "B-tree";
if ( argv.length > 1 ) {
if ( argv[1].equalsIgnoreCase("binary")) {
algoName = "Binary";
algorithm = DbSearcher.BINARY_ALGORITHM;
} else if ( argv[1].equalsIgnoreCase("memory") ) {
algoName = "Memory";
algorithm = DbSearcher.MEMORY_ALGORITYM;
}
}
try {
System.out.println("initializing "+algoName+" ... ");
DbConfig config = new DbConfig();
DbSearcher searcher = new DbSearcher(config, argv[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//define the method
Method method = null;
switch ( algorithm )
{
case DbSearcher.BTREE_ALGORITHM:
method = searcher.getClass().getMethod("btreeSearch", String.class);
break;
case DbSearcher.BINARY_ALGORITHM:
method = searcher.getClass().getMethod("binarySearch", String.class);
break;
case DbSearcher.MEMORY_ALGORITYM:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
}
System.out.println("+----------------------------------+");
System.out.println("| ip2region test shell |");
System.out.println("| Author: chenxin619315@gmail.com |");
System.out.println("| Type 'quit' to exit program |");
System.out.println("+----------------------------------+");
double sTime = 0, cTime = 0;
String line = null;
DataBlock dataBlock = null;
while ( true ) {
System.out.print("ip2region>> ");
line = reader.readLine().trim();
if ( line.length() < 2 ) continue;
if ( line.equalsIgnoreCase("quit") ) break;
if ( Util.isIpAddress(line) == false ) {
System.out.println("Error: Invalid ip address");
continue;
}
sTime = System.nanoTime();
dataBlock = (DataBlock) method.invoke(searcher, line);
cTime = (System.nanoTime() - sTime) / 1000000;
System.out.printf("%s in %.5f millseconds\n", dataBlock, cTime);
}
reader.close();
searcher.close();
System.out.println("+--Bye");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DbMakerConfigException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -1,96 +0,0 @@
package org.lionsoul.ip2region.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbMakerConfigException;
import org.lionsoul.ip2region.DbSearcher;
/**
* data check class
*
* @author koma<komazhang@foxmail.com>
**/
public class TestUnit {
public static void main(String[] args) {
try {
DbSearcher _searcher = new DbSearcher(new DbConfig(), "./data/ip2region.db");
BufferedReader bfr = new BufferedReader(new FileReader("./data/ip.merge.txt"));
BufferedWriter bwr = new BufferedWriter(new FileWriter("./data/error_log.txt", true));
int errCount = 0;
int lineCount = 0;
String str = null;
while ( (str = bfr.readLine()) != null ) {
StringBuffer line = new StringBuffer(str);
//get first ip
int first_idx = line.indexOf("|");
String first_ip = line.substring(0, first_idx);
line = new StringBuffer( line.substring(first_idx + 1) );
//get second ip
int second_idx = line.indexOf("|");
String second_ip = line.substring(0, second_idx);
//get addr
String source_region = line.substring(second_idx + 1);
//search from DbSearcher
System.out.println("+---Start, start to search");
System.out.println("+---[Info]: Source region = "+source_region);
System.out.println("+---[Info]: Step1, search for first IP: "+first_ip);
DataBlock fdata = _searcher.binarySearch(first_ip);
if ( ! fdata.getRegion().equalsIgnoreCase( source_region ) ) {
System.out.println("[Error]: Search first IP failed, DB region = "+fdata.getRegion());
bwr.write("[Source]: Region: "+fdata.getRegion());
bwr.newLine();
bwr.write("[Source]: First Ip: "+first_ip);
bwr.newLine();
bwr.write("[DB]: Region: "+fdata.getRegion());
bwr.newLine();
bwr.flush();
errCount++;
}
System.out.println("+---[Info]: Step2, search for second IP: "+second_ip);
DataBlock sdata = _searcher.btreeSearch(second_ip);
if ( ! sdata.getRegion().equalsIgnoreCase( source_region ) ) {
System.out.println("[Error]: Search second IP failed, DB region = "+sdata.getRegion());
bwr.write("[Source]: Region: "+sdata.getRegion());
bwr.newLine();
bwr.write("[Source]: First Ip: "+second_ip);
bwr.newLine();
bwr.write("[DB]: Region: "+sdata.getRegion());
bwr.newLine();
bwr.flush();
errCount++;
}
lineCount++;
}
bwr.close();
bfr.close();
System.out.println("+---Done, search complished");
System.out.println("+---Statistics, Error count = "+errCount
+", Total line = "+lineCount
+", Fail ratio = "+((float)(errCount/lineCount))*100+"%");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DbMakerConfigException e) {
e.printStackTrace();
} catch ( Exception e ) {
e.printStackTrace();
}
}
}

View File

@ -1,57 +0,0 @@
package org.lionsoul.ip2region.test;
import org.lionsoul.ip2region.Util;
/**
* project test script
*
* @author chenxin<chenxin619315@gmail.com>
*/
public class TestUtil
{
public static void main(String[] argv)
{
/* //1. test the ip2long
String[] ipSet = new String[]{
"120.24.78.68",
"120.24.229.68",
"120.24.87.145",
"218.17.162.99"
};
for ( String ip : ipSet )
{
int ipInt = Util.ip2Int(ip);
System.out.println("src ip: " + ip + ", ip2Int: " + ipInt + ", int2IP: " + Util.int2IP(ipInt));
}*/
/* int[] arr = new int[]{12344, -1234, 2146789, 0, -1024};
byte[] b = new byte[arr.length * 4];
//write the int
System.out.println("+--Testing writeInt ... ");
int i, idx = 0;
for ( i = 0; i < b.length; i += 4 )
{
System.out.println("offset: " + i);
Util.writeInt(b, i, arr[idx++]);
}
System.out.println("|----[Ok]");
//read the int
System.out.println("+--Testing getInt ... ");
idx = 0;
for ( i = 0; i < b.length; i += 4 )
{
System.out.println(arr[idx++]+", " + Util.getInt(b, i));
}
System.out.println("|----[Ok]");*/
/* HeaderBlock headerBlock = new HeaderBlock(241658345, 2134785);
byte[] b = headerBlock.getBytes();
System.out.println(headerBlock.getIndexStartIp() + ", " + headerBlock.getIndexPtr());
System.out.println(Util.getInt(b, 0) + ", " + Util.getInt(b, 4));*/
System.out.println(Util.ip2long("255.255.255.0"));
}
}

View File

@ -1,443 +0,0 @@
--[[
Ip2region lua binding
@author chenxin<chenxin619315@gmail.com>
@date 2018/10/02
]]--
require("bit32");
local INDEX_BLOCK_LENGTH = 12;
local TOTAL_HEADER_LENGTH = 8192;
local _M = {
dbFile = "",
dbFileHandler = "",
dbBinStr = "",
HeaderSip = "",
HeaderPtr = "",
headerLen = 0,
firstIndexPtr = 0,
lastIndexPtr = 0,
totalBlocks = 0
};
_G["Ip2region"] = _M;
-- set the __index to itself
_M.__index = _M;
-- set the print meta-method
_M.__tostring = function(table)
local t = {
"dbFile=" .. table.dbFile,
-- "dbFileHandler=" .. table.dbFileHandler,
"headerLen=" .. table.headerLen,
"firstIndexPtr" .. table.firstIndexPtr,
"lastIndexPtr" .. table.lastIndexPtr,
"totalBlocks" .. table.totalBlocks
};
return table.concat(t, ",");
end
--[[
construct method
@param obj
@return Ip2region object
--]]
function _M.new(dbFile)
obj = {};
setmetatable(obj, _M);
obj.dbFile = dbFile;
return obj;
end
--[[
internal function to get a integer from a binary string
@param dbBinStr
@param idx
@return Integer
]]--
function getLong(bs, idx)
local a1 = string.byte(string.sub(bs, idx, idx));
local a2 = bit32.lshift(string.byte(string.sub(bs, idx+1, idx+1)), 8);
local a3 = bit32.lshift(string.byte(string.sub(bs, idx+2, idx+2)), 16);
local a4 = bit32.lshift(string.byte(string.sub(bs, idx+3, idx+3)), 24);
local val = bit32.bor(a1, a2);
val = bit32.bor(val, a3);
val = bit32.bor(val, a4);
return val;
end
--[[
internal function to convert the string ip to a long value
@param ip
@return Integer
]]--
function _M.ip2long(self, ip)
-- dynamic arguments checking
-- to support object.ip2long and object:ip2long access
if ( type(self) == "string") then
ip = self;
end
local ini = 1;
local iip = 0;
local off = 24;
while true do
local pos = string.find(ip, '.', ini, true);
if ( not pos ) then
break;
end
local sub = string.sub(ip, ini, pos - 1);
if ( string.len(sub) < 1 ) then
return nil;
end
iip = bit32.bor(iip, bit32.lshift(tonumber(sub), off));
ini = pos + 1;
off = off - 8;
end
-- check if it is a valid ip address
if ( off ~= 0 or ini > string.len(ip) ) then
return nil;
end
local sub = string.sub(ip, ini);
if ( string.len(sub) < 1 ) then
return nil;
end
return bit32.bor(iip, bit32.lshift(tonumber(sub), off));
end
--[[
internal function to get the whole content of a file
@param file
@return String
]]--
function get_file_contents(file)
local fi = io.input(file);
if ( not fi ) then
return nil;
end
local str = io.read("*a");
io.close();
return str;
end
--[[
set the current db file path
@param dbFile
]]--
function _M:setDbFile(dbFile)
self.dbFile = dbFile;
end
--[[
all the db binary string will be loaded into memory
then search the memory only and this will a lot faster than disk base search
@Note: invoke it once before put it to public invoke could make it thread safe
@param ip
@return table or nil for failed
]]--
function _M:memorySearch(ip)
-- string ip conversion
if ( type(ip) == "string" ) then
ip = self:ip2long(ip);
if ( ip == nil ) then
return nil;
end
end;
-- check and load the binary string for the first time
if ( self.dbBinStr == "" ) then
self.dbBinStr = get_file_contents(self.dbFile);
if ( not self.dbBinStr ) then
return nil;
end
self.firstIndexPtr = getLong(self.dbBinStr, 1);
self.lastIndexPtr = getLong(self.dbBinStr, 5);
self.totalBlocks = (self.lastIndexPtr - self.firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
end
-- binary search to define the data
local l = 0;
local h = self.totalBlocks;
local dataPtr = 0;
while ( l <= h ) do
local m = math.floor((l + h) / 2);
local p = self.firstIndexPtr + m * INDEX_BLOCK_LENGTH;
local sip = getLong(self.dbBinStr, p + 1);
if ( ip < sip ) then
h = m - 1;
else
local eip = getLong(self.dbBinStr, p + 5); -- 4 + 1
if ( ip > eip ) then
l = m + 1;
else
dataPtr = getLong(self.dbBinStr, p + 9); -- 8 + 1
break;
end
end
end
-- not matched just stop it here
if ( dataPtr == 0 ) then return nil end
-- get the data
local dataLen = bit32.band(bit32.rshift(dataPtr, 24), 0xFF);
dataPtr = bit32.band(dataPtr, 0x00FFFFFF);
local dptr = dataPtr + 5; -- 4 + 1
return {
city_id = getLong(self.dbBinStr, dataPtr),
region = string.sub(self.dbBinStr, dptr, dptr + dataLen - 5)
};
end
--[[
get the data block through the specified ip address
or long ip numeric with binary search algorithm
@param ip
@return table or nil for failed
]]--
function _M:binarySearch(ip)
-- check and conver the ip address
if ( type(ip) == "string" ) then
ip = self:ip2long(ip);
if ( ip == nil ) then
return nil;
end
end
if ( self.totalBlocks == 0 ) then
-- check and open the original db file
self.dbFileHandler = io.open(self.dbFile, "r");
if ( not self.dbFileHandler ) then
return nil;
end
self.dbFileHandler:seek("set", 0);
local superBlock = self.dbFileHandler:read(8);
self.firstIndexPtr = getLong(superBlock, 1); -- 0 + 1
self.lastIndexPtr = getLong(superBlock, 5); -- 4 + 1
self.totalBlocks = (self.lastIndexPtr-self.firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
end
-- binary search to define the data
local l = 0;
local h = self.totalBlocks;
local dataPtr = 0;
while ( l <= h ) do
local m = math.floor((l + h) / 2);
local p = m * INDEX_BLOCK_LENGTH;
self.dbFileHandler:seek("set", self.firstIndexPtr + p);
local buffer = self.dbFileHandler:read(INDEX_BLOCK_LENGTH);
local sip = getLong(buffer, 1); -- 0 + 1
if ( ip < sip ) then
h = m - 1;
else
local eip = getLong(buffer, 5); -- 4 + 1
if ( ip > eip ) then
l = m + 1;
else
dataPtr = getLong(buffer, 9); -- 8 + 1
break;
end
end
end
-- not matched just stop it here
if ( dataPtr == 0 ) then return nil; end
-- get the data
local dataLen = bit32.band(bit32.rshift(dataPtr, 24), 0xFF);
dataPtr = bit32.band(dataPtr, 0x00FFFFFF);
self.dbFileHandler:seek("set", dataPtr);
local data = self.dbFileHandler:read(dataLen);
return {
city_id = getLong(data, 1), -- 0 + 1
region = string.sub(data, 5) -- 4 + 1
};
end
--[[
get the data block associated with the specified ip with b-tree search algorithm
@param ip
@return table or nil for failed
]]--
function _M:btreeSearch(ip)
-- string ip to integer conversion
if ( type(ip) == "string" ) then
ip = self:ip2long(ip);
if ( ip == nil ) then
return nil;
end
end
-- check and load the header
if ( self.headerLen == 0 ) then
-- check and open the original db file
self.dbFileHandler = io.open(self.dbFile, 'r');
if ( not self.dbFileHandler ) then
return nil;
end
self.dbFileHandler:seek("set", 8);
local buffer = self.dbFileHandler:read(TOTAL_HEADER_LENGTH);
-- fill the header
local i = 0;
local idx = 0;
self.HeaderSip = {};
self.HeaderPtr = {};
for i=0, TOTAL_HEADER_LENGTH, 8 do
local startIp = getLong(buffer, i + 1); -- 0 + 1
local dataPtr = getLong(buffer, i + 5); -- 4 + 1
if ( dataPtr == 0 ) then
break;
end
table.insert(self.HeaderSip, startIp);
table.insert(self.HeaderPtr, dataPtr);
idx = idx + 1;
end
self.headerLen = idx;
end
-- 1. define the index block with the binary search
local l = 0;
local h = self.headerLen;
local sptr = 0;
local eptr = 0;
while ( l <= h ) do
local m = math.floor((l + h) / 2);
-- perfetc matched, just return it
if ( ip == self.HeaderSip[m] ) then
if ( m > 0 ) then
sptr = self.HeaderPtr[m-1];
eptr = self.HeaderPtr[m ];
else
sptr = self.HeaderPtr[m ];
eptr = self.HeaderPtr[m+1];
end
break;
end
-- less then the middle value
if ( ip < self.HeaderSip[m] ) then
if ( m == 0 ) then
sptr = self.HeaderPtr[m ];
eptr = self.HeaderPtr[m+1];
break;
elseif ( ip > self.HeaderSip[m-1] ) then
sptr = self.HeaderPtr[m-1];
eptr = self.HeaderPtr[m ];
break;
end
h = m - 1;
else
if ( m == self.headerLen - 1 ) then
sptr = self.HeaderPtr[m-1];
eptr = self.HeaderPtr[m ];
break;
elseif ( ip <= self.HeaderSip[m+1] ) then
sptr = self.HeaderPtr[m ];
eptr = self.HeaderPtr[m+1];
break;
end
l = m + 1;
end
end
-- match nothing just stop it
if ( sptr == 0 ) then return nil; end
-- 2. search the index blocks to define the data
self.dbFileHandler:seek("set", sptr);
local blockLen = eptr - sptr;
local index = self.dbFileHandler:read(blockLen + INDEX_BLOCK_LENGTH);
local dataPtr = 0;
l = 0;
h = blockLen / INDEX_BLOCK_LENGTH;
while ( l <= h ) do
local m = math.floor((l + h) / 2);
local p = m * INDEX_BLOCK_LENGTH;
local sip = getLong(index, p + 1); -- 0 + 1
if ( ip < sip ) then
h = m - 1;
else
local eip = getLong(index, p + 5); -- 4 + 1
if ( ip > eip ) then
l = m + 1;
else
dataPtr = getLong(index, p + 9); -- 8 + 1
break;
end
end
end
-- not matched
if ( dataPtr == 0 ) then return nil; end
-- 3. get the data
local dataLen = bit32.band(bit32.rshift(dataPtr, 24), 0xFF);
dataPtr = bit32.band(dataPtr, 0x00FFFFFF);
self.dbFileHandler:seek("set", dataPtr);
local data = self.dbFileHandler:read(dataLen);
return {
city_id = getLong(data, 1), -- 0 + 1
region = string.sub(data, 5) -- 4 + 1
};
end
--[[
close the object and do the basic gc
]]--
function _M.close(self)
if ( self.dbFileHandler ~= "" ) then
self.dbFileHandler:close();
end
if ( self.dbBinStr ~= "" ) then
self.dbBinStr = nil;
end
end
return _M;

View File

@ -1,59 +0,0 @@
# Lua ip2region binding
### 一,如何测试
* 1, cd到ip2region/binding/lua/根目录
* 2, 运行testSearcher测试程序
```shell
lua testSearcher.lua ../../data/ip2region.db
```
* 3, 输入ip地址开始测试即可
```shell
initializing btree
+----------------------------------+
| ip2region test script |
| Author: chenxin619315@gmail.com |
| Type 'quit' to exit program |
+----------------------------------+
ip2region>> 1.2.3.4
0|美国|0|华盛顿|0|0 in 8.001000 millseconds
ip2region>> 101.233.153.103
2163|中国|0|广东省|深圳市|鹏博士 in 0.176000 millseconds
ip2region>>
```
### 二,如何使用
* 1, 将Ip2region.lua拷贝到你的package.path下
* 2, 通过如下流程在你的lua程序中使用
```lua
-- 包含模块
local Ip2region = require "Ip2region";
-- 创建查询对象
-- 设置ip2region.db的文件地址dbFile表示ip2region.db数据库文件的地址
-- 注意new方法是通过“.”调用,而不是“:”
local ip2region = Ip2region.new("ip2region.db file path");
-- 也可以通过如下方式设置dbFile
-- ip2region.dbFile = "ip2region.db file path";
-- ip2region.setDbFile("ip2region.db file path");
local data;
-- 查询,备注,尽量请使用“:”调用方法,使用“.”需要主动传递ip2region对象参数
-- 1binary查询
data = ip2region:binarySearch("101.233.153.103");
-- 2btree查询
data = ip2region:btreeSearch("101.233.153.103");
-- 3memory查询
data = ip2region:memorySearch("101.233.153.103");
-- 返回结果如下
print("city_id=", data.city_id, "region=", data.region);
```
### 三,备注
* 1Ip2region模块的位运算依赖了bit32模块这个是lua 5.2才开始支持的。

View File

@ -1,85 +0,0 @@
--[[
ip2region lua client test script
@author chenxin<chenxin619315@gmail.com>
]]--
-- check the command line arguments
if ( not arg[1] ) then
print([[
Usage: lua testSearcher.lua [ip2region db file] [algorithm]
+-Optional Algorithm: binary, b-tree, memory]]);
os.exit();
end
local Ip2region = require "Ip2region";
-- local cjson = require "cjson";
-- local socket = require "socket";
-- check and parse the dbFile and the method algorithm
-- Create a new ip2region object by the new interface
local ip2region = Ip2region.new(arg[1]);
-- reset the dbFile by the follow two ways:
-- ip2region.dbFile = arg[1];
-- ip2region:setDbFile(arg[1]);
local algorithm = "btree";
if ( arg[2] ~= nil ) then
local arg_2 = string.lower(arg[2]);
if ( arg_2 ~= "binary" and arg_2 ~= "memory" ) then
algorithm = "binary";
elseif ( arg_2 == "memory" ) then
algorithm = "memory";
end
end
-- local data = searcher:memorySearch("120.79.17.142");
-- local data = searcher:binarySearch("120.79.17.142");
-- local data = searcher:btreeSearch("120.79.17.142");
print("initializing " .. algorithm ..[[
+----------------------------------+
| ip2region test script |
| Author: chenxin619315@gmail.com |
| Type 'quit' to exit program |
+----------------------------------+]]
);
while ( true ) do
io.write("ip2region>> ");
io.input(io.stdin);
local line = io.read();
if ( line == nil ) then
-- do nothing
break;
elseif ( line == "quit" ) then
break;
elseif ( ip2region.ip2long(line) == nil ) then
print("Invalid ip address=", line);
else
local data;
local s_time = os.clock();
if ( algorithm == "btree" ) then
data = ip2region:btreeSearch(line);
elseif ( algorithm == "binary" ) then
data = ip2region:binarySearch(line);
elseif ( algorithm == "memory" ) then
data = ip2region:memorySearch(line);
end
local cost_time = (os.clock() - s_time) * 1000; -- to millseconds
if ( data == nil ) then
io.write("Failed for ip=", line, " is it a valid ip address ?");
else
io.write(string.format("%u|%s in %5f millseconds\n", data.city_id, data.region, cost_time));
end
end
end
-- close the object
-- print(ip2region);
ip2region:close();

View File

@ -1,28 +0,0 @@
# ip2region luc c module Make file
# @author chenxin<chenxin619315@gmail.com>
# @date 2018/10/05
# @Note
# Please modify the LIBS and the LIB_DIR to fit you system
#
VER = 5.2
CC = gcc
LIBS = -I ../c/ -I /usr/include/lua$(VER)/
FFLAGS = -O2 -Wall -fPIC
SO_FILE = Ip2region.so
LIB_DIR = /usr/local/share/lua/$(VER)
all: ../c/ip2region.c ../c/ip2region.h lua_ip2region.c
$(CC) $(FFLAGS) $(LIBS) ../c/ip2region.c lua_ip2region.c -fPIC -shared -o $(SO_FILE)
install:
sudo mkdir -p $(LIB_DIR); \
sudo cp $(SO_FILE) $(LIB_DIR);\
echo "install Ip2region to $(LIB_DIR) successfully.";\
clean:
find . -name \*.so | xargs rm -f
find . -name \*.o | xargs rm -f
.PHONY: clean

View File

@ -1,74 +0,0 @@
# Lua ip2region c module binding
### 一,如何安装
* 1, cd到ip2region/binding/lua_c/根目录
* 2, 运行如下命令
```
make
sudo make install
```
* 3, 关于Makefile你可能需要更改里面的VER(版本号)和LIB_DIR(lua的so lib目录)来适应你的系统
```shell
VER = 5.2
CC = gcc
LIBS = -I ../c/ -I /usr/include/lua$(VER)/
FFLAGS = -O2 -Wall -fPIC
SO_FILE = Ip2region.so
LIB_DIR = /usr/local/share/lua/$(VER)
```
### 二,如何测试
* 1, cd到ip2region/binding/lua_c/根目录
* 2, 运行testSearcher测试程序
```shell
lua testSearcher.lua ../../data/ip2region.db
```
* 3, 输入ip地址开始测试即可
```shell
initializing btree
+----------------------------------+
| ip2region test script |
| Author: chenxin619315@gmail.com |
| Type 'quit' to exit program |
+----------------------------------+
ip2region>> 1.2.3.4
0|美国|0|华盛顿|0|0 in 0.100000 millseconds
ip2region>> 101.233.153.103
2163|中国|0|广东省|深圳市|鹏博士 in 0.045000 millseconds
ip2region>>
```
### 三,如何使用
* 1, 先参考第一步安装把Ip2region.so安装到你系统lua的lib目录下
* 2, 通过如下流程在你的lua程序中使用
```lua
-- 包含模块
local Ip2region = require "Ip2region";
-- 创建查询对象
-- 设置ip2region.db的文件地址dbFile表示ip2region.db数据库文件的地址
-- 注意new方法是通过“.”调用,而不是“:”
local ip2region = Ip2region.new("ip2region.db file path");
local data;
-- 查询,备注,尽量请使用“:”调用方法,使用“.”需要主动传递ip2region对象参数
-- 1binary查询
data = ip2region:binarySearch("101.233.153.103");
-- 2btree查询
data = ip2region:btreeSearch("101.233.153.103");
-- 3memory查询
data = ip2region:memorySearch("101.233.153.103");
-- 返回结果如下
print("city_id=", data.city_id, "region=", data.region);
```
### 四,备注
* 1c模块的Ip2region以来binding/c/的实现请保持binding/c/存在并且和lua_c模块同目录。
* 2Ip2region的c模块拥有和c模块几乎等同的性能生产建议使用lua_c模块代替纯lua模块的使用。

View File

@ -1,232 +0,0 @@
/**
* Ip2region lua c binding
*
* @author chenxin<chenxin619315@gmail.com>
* @date 2018/10/04
*/
#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>
#include "../c/ip2region.h"
#define L_METATABLE_NAME "Ip2region_MT"
/** create a new ip2region object with a specified dbFile */
static int lua_ip2region_new(lua_State *L)
{
ip2region_entry *self;
const char *dbFile;
/* Check the arguments are valid */
dbFile = luaL_checkstring(L, 1);
if ( dbFile == NULL ) {
luaL_error(L, "dbFile cannot be empty");
}
/* Create the user data and push it onto the stack */
self = (ip2region_entry *) lua_newuserdata(L, sizeof(ip2region_entry));
/* Push the metatable onto the stack */
luaL_getmetatable(L, L_METATABLE_NAME);
/* Set the metatable on the userdata */
lua_setmetatable(L, -2);
/* Initialize the entry */
ip2region_create(self, dbFile);
return 1;
}
/** destroy the specified ip2region instance */
static int lua_ip2region_destroy(lua_State *L)
{
ip2region_entry *self;
self = (ip2region_entry *) luaL_checkudata(L, 1, L_METATABLE_NAME);
ip2region_destroy(self);
return 0;
}
#define get_search_args(L, entry, ip) \
do { \
luaL_argcheck(L, lua_gettop(L) == 2, 2, "Object and ip address needed"); \
entry = (ip2region_entry *) luaL_checkudata(L, 1, L_METATABLE_NAME); \
ip = luaL_checkstring(L, 2); \
} while (0); \
#define set_search_result(L, data) \
do { \
lua_newtable(L); \
lua_pushinteger(L, data.city_id); \
lua_setfield(L, -2, "city_id"); \
lua_pushfstring(L, "%s", data.region); \
lua_setfield(L, -2, "region"); \
} while (0); \
/** ip2region_memory_search wrapper */
static int lua_ip2region_memory_search(lua_State *L)
{
ip2region_entry *self;
const char *addr;
datablock_entry data;
// luaL_argcheck(L, lua_gettop(L) == 2, 2, "object and ip address needed");
// self = (ip2region_entry *) luaL_checkudata(L, 1, L_METATABLE_NAME);
// addr = luaL_checkstring(L, 2);
/* Check and get the search parameters */
get_search_args(L, self, addr);
/* do the memory search */
if ( ip2region_memory_search(self, ip2long(addr), &data) == 0 ) {
lua_pushnil(L);
return 1;
}
// lua_newtable(L);
// lua_pushinteger(L, data.city_id);
// lua_setfield(L, -2, "city_id");
// lua_pushfstring(L, "%s", data.region);
// lua_setfield(L, -2, "region");
set_search_result(L, data);
return 1;
}
/** ip2region_binary_search wrapper */
static int lua_ip2region_binary_search(lua_State *L)
{
ip2region_entry *self;
const char *addr;
datablock_entry data;
/* Check and get the search parameters */
get_search_args(L, self, addr);
/* Do the binary search */
if ( ip2region_binary_search(self, ip2long(addr), &data) == 0 ) {
lua_pushnil(L);
return 1;
}
/* Set the return value */
set_search_result(L, data);
return 1;
}
/** ip2region_btree_search wrapper */
static int lua_ip2region_btree_search(lua_State *L)
{
ip2region_entry *self;
const char *addr;
datablock_entry data;
/* Check and get the search parameters */
get_search_args(L, self, addr);
/* Do the btree search */
if ( ip2region_btree_search(self, ip2long(addr), &data) == 0 ) {
lua_pushnil(L);
return 1;
}
/* Set the return value */
set_search_result(L, data);
return 1;
}
/** ip2long wrapper */
static int lua_ip2long(lua_State *L)
{
int argc;
const char *addr;
uint_t ipval;
argc = lua_gettop(L);
if ( argc == 1 ) {
addr = luaL_checkstring(L, 1);
} else {
luaL_checkudata(L, 1, L_METATABLE_NAME);
addr = luaL_checkstring(L, 2);
}
if ( (ipval = ip2long(addr)) == 0 ) {
lua_pushnil(L);
return 1;
}
lua_pushinteger(L, (ipval & 0x7FFFFFFF));
return 1;
}
static int lua_ip2region_tostring(lua_State *L)
{
ip2region_entry *self;
self = (ip2region_entry *) luaL_checkudata(L, 1, L_METATABLE_NAME);
/* Push the string to return to lua */
lua_pushfstring(L,
"dbFile=%s, headerLen=%d, fristIndexPtr=%d, lastIndexPtr=%d, totalBlocks=%d",
self->dbFile, self->headerLen, self->firstIndexPtr,
self->lastIndexPtr, self->totalBlocks
);
return 1;
}
/** module method array */
static const struct luaL_Reg ip2region_methods[] = {
// { "new", lua_ip2region_new },
// { "ip2long", lua_ip2long },
{ "memorySearch", lua_ip2region_memory_search },
{ "binarySearch", lua_ip2region_binary_search },
{ "btreeSearch", lua_ip2region_btree_search },
{ "close", lua_ip2region_destroy },
{ "__gc", lua_ip2region_destroy },
{ "__tostring", lua_ip2region_tostring },
{ NULL, NULL },
};
/** module function array */
static const struct luaL_Reg ip2region_functions[] = {
{ "new", lua_ip2region_new },
{ "ip2long", lua_ip2long },
{ NULL, NULL }
};
/** module open function interface */
int luaopen_Ip2region(lua_State *L)
{
/* Create a metatable and push it onto the stack */
luaL_newmetatable(L, L_METATABLE_NAME);
/* Duplicate the metatable on the stack */
lua_pushvalue(L, -1);
/* Pop the first metatable off the stack
* and assign it to the __index of the second one.
* so we set the metatable to the table itself.
*/
lua_setfield(L, -2, "__index");
/* Set the methods fo the metatable that could and should be
* access via object:func in lua block
*/
luaL_setfuncs(L, ip2region_methods, 0);
luaL_setfuncs(L, ip2region_functions, 0);
/* Finally register the object.func functions
* into the table witch at the top of the stack */
// luaL_newlib(L, ip2region_functions);
return 1;
}

View File

@ -1,86 +0,0 @@
--[[
ip2region lua client test script
@author chenxin<chenxin619315@gmail.com>
]]--
-- check the command line arguments
if ( not arg[1] ) then
print([[
Usage: lua testSearcher.lua [ip2region db file] [algorithm]
+-Optional Algorithm: binary, b-tree, memory]]);
os.exit();
end
local Ip2region = require "Ip2region";
-- local cjson = require "cjson";
-- local socket = require "socket";
-- check and parse the dbFile and the method algorithm
-- Create a new ip2region object by the new interface
local ip2region = Ip2region.new(arg[1]);
-- reset the dbFile by the follow two ways:
-- ip2region.dbFile = arg[1];
-- ip2region:setDbFile(arg[1]);
local algorithm = "btree";
if ( arg[2] ~= nil ) then
local arg_2 = string.lower(arg[2]);
if ( arg_2 ~= "binary" and arg_2 ~= "memory" ) then
algorithm = "binary";
elseif ( arg_2 == "memory" ) then
algorithm = "memory";
end
end
-- local data = searcher:memorySearch("120.79.17.142");
-- local data = searcher:binarySearch("120.79.17.142");
-- local data = searcher:btreeSearch("120.79.17.142");
print("initializing " .. algorithm ..[[
+----------------------------------+
| ip2region test script |
| Author: chenxin619315@gmail.com |
| Type 'quit' to exit program |
+----------------------------------+]]
);
while ( true ) do
io.write("ip2region>> ");
io.input(io.stdin);
local line = io.read();
if ( line == nil ) then
-- do nothing
break;
elseif ( line == "quit" ) then
break;
elseif ( Ip2region.ip2long(line) == nil ) then
print("Invalid ip address=", line);
else
local data;
local s_time = os.clock();
if ( algorithm == "btree" ) then
data = ip2region:btreeSearch(line);
elseif ( algorithm == "binary" ) then
data = ip2region:binarySearch(line);
elseif ( algorithm == "memory" ) then
data = ip2region:memorySearch(line);
end
local cost_time = (os.clock() - s_time) * 1000; -- to millseconds
if ( data == nil ) then
io.write("Failed for ip=", line, " is it a valid ip address ?");
else
io.write(string.format("%u|%s in %5f millseconds\n", data.city_id, data.region, cost_time));
end
end
end
-- close the object
-- Also the lua gc will invoke it automatically
-- print(ip2region);
ip2region:close();

View File

@ -1,3 +0,0 @@
# 说明
- 编译本模块时,请手动链接对../c/ip2region.c文件的依赖。

View File

@ -1,44 +0,0 @@
ngx_addon_name="ngx_ip2region_module"
IP2REGION_CORE_MODULES=" \
ngx_ip2region_module \
"
IP2REGION_DEPS=" \
$ngx_addon_dir/ip2region.h \
$ngx_addon_dir/ngx_ip2region.h \
"
IP2REGION_CORE_SRCS=" \
$ngx_addon_dir/ip2region.c \
$ngx_addon_dir/ngx_ip2region_module.c \
"
if [ -f auto/module ] ; then
ngx_module_incs=$ngx_addon_dir
ngx_module_deps=$IP2REGION_DEPS
if [ $ngx_module_link = DYNAMIC ] ; then
ngx_module_name="$IP2REGION_CORE_MODULES"
ngx_module_srcs="$IP2REGION_CORE_SRCS"
. auto/module
else
ngx_module_type=CORE
ngx_module_name=$IP2REGION_CORE_MODULES
ngx_module_srcs=$IP2REGION_CORE_SRCS
. auto/module
fi
else
CORE_MODULES="$CORE_MODULES $IP2REGION_CORE_MODULES"
NGX_ADDON_DEPS="$NGX_ADDON_DEPS $IP2REGION_DEPS"
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $IP2REGION_CORE_SRCS"
CFLAGS="$CFLAGS -I$ngx_addon_dir "
fi

View File

@ -1,23 +0,0 @@
#ifndef __NGX_IP2REGION_H__
#define __NGX_IP2REGION_H__
#ifdef __cplusplus
extern "C" {
#endif
#include "../c/ip2region.h"
typedef struct ngx_ip2region_conf_s {
ngx_str_t db_file;
ngx_uint_t algo;
} ngx_ip2region_conf_t;
typedef uint_t (*search_func_ptr)(ip2region_t, uint_t, datablock_t);
extern ngx_int_t ngx_ip2region_search(ngx_str_t *addr_text, ngx_str_t *isp, ngx_str_t *city);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,260 +0,0 @@
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_ip2region.h"
static void *ngx_ip2region_create_conf(ngx_cycle_t *cycle);
static char *ngx_ip2region_init_conf(ngx_cycle_t *cycle, void *conf);
static ngx_int_t ngx_ip2region_init_process(ngx_cycle_t *cycle);
static void ngx_ip2region_exit_process(ngx_cycle_t *cycle);
static ip2region_entry g_ip2region_entry;
search_func_ptr ip2region_search_func;
#define NGX_IP2REGION_MEMORY 0
#define NGX_IP2REGION_BINARY 1
#define NGX_IP2REGION_BTREE 2
static ngx_conf_enum_t ngx_ip2region_search_algo[] = {
{ ngx_string("memory"), NGX_IP2REGION_MEMORY },
{ ngx_string("binary"), NGX_IP2REGION_BINARY },
{ ngx_string("btree"), NGX_IP2REGION_BTREE},
{ ngx_null_string, 0 }
};
static ngx_command_t ngx_ip2region_commands[] = {
{
ngx_string("ip2region_db_file"),
NGX_MAIN_CONF | NGX_DIRECT_CONF | NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
0,
offsetof(ngx_ip2region_conf_t, db_file),
NULL
},
{
ngx_string("ip2region_algo"),
NGX_MAIN_CONF | NGX_DIRECT_CONF | NGX_CONF_TAKE1,
ngx_conf_set_enum_slot,
0,
offsetof(ngx_ip2region_conf_t, algo),
&ngx_ip2region_search_algo
},
ngx_null_command
};
static ngx_core_module_t ngx_ip2region_module_ctx = {
ngx_string("ip2region"),
ngx_ip2region_create_conf,
ngx_ip2region_init_conf,
};
ngx_module_t ngx_ip2region_module = {
NGX_MODULE_V1,
&ngx_ip2region_module_ctx, /* module context */
ngx_ip2region_commands, /* module directives */
NGX_CORE_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
ngx_ip2region_init_process, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
ngx_ip2region_exit_process, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *
ngx_ip2region_create_conf(ngx_cycle_t *cycle)
{
ngx_ip2region_conf_t *ip2region_conf;
ip2region_conf = ngx_pcalloc(cycle->pool, sizeof(ngx_ip2region_conf_t));
if(ip2region_conf == NULL) {
return NULL;
}
ip2region_conf->algo = NGX_CONF_UNSET_UINT;
return ip2region_conf;
}
static char *
ngx_ip2region_init_conf(ngx_cycle_t *cycle, void *conf)
{
ngx_ip2region_conf_t *ip2region_conf = (ngx_ip2region_conf_t *)conf;
if(ip2region_conf->db_file.len == 0) {
//ngx_str_set(&ip2region_conf->db_file, "conf/ip2region.db");
return NGX_CONF_OK;
}
if(ngx_conf_full_name(cycle, &ip2region_conf->db_file, 0) != NGX_OK) {
return NGX_CONF_ERROR;
}
ngx_log_debug1(NGX_LOG_INFO, ngx_cycle->log, 0, "%V", &ip2region_conf->db_file);
if(ip2region_conf->algo == NGX_CONF_UNSET_UINT) {
ip2region_conf->algo = NGX_IP2REGION_MEMORY;
}
return NGX_CONF_OK;
}
static ngx_int_t
ngx_ip2region_init_process(ngx_cycle_t *cycle)
{
ngx_ip2region_conf_t *conf = (ngx_ip2region_conf_t *)ngx_get_conf(ngx_cycle->conf_ctx, ngx_ip2region_module);
if(conf->db_file.len == 0) {
ngx_log_debug0(NGX_LOG_INFO, ngx_cycle->log, 0, "ip2region not init");
return NGX_OK;
}
if(!ip2region_create(&g_ip2region_entry, (char *)conf->db_file.data)) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "ip2region create failed: %V", &conf->db_file);
return NGX_ERROR;
}
switch(conf->algo) {
default:
case NGX_IP2REGION_MEMORY:
ip2region_search_func = ip2region_memory_search;
break;
case NGX_IP2REGION_BINARY:
ip2region_search_func = ip2region_binary_search;
break;
case NGX_IP2REGION_BTREE:
ip2region_search_func = ip2region_btree_search;
break;
}
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0, "ip2region create succcess: algo=%ui", conf->algo);
return NGX_OK;
}
static void
ngx_ip2region_exit_process(ngx_cycle_t *cycle)
{
ip2region_destroy(&g_ip2region_entry);
ngx_log_debug0(NGX_LOG_INFO, ngx_cycle->log, 0, "ip2region destroy");
}
static ngx_inline u_char *
ngx_strrchr(u_char *first, u_char *p, u_char c)
{
while(p >= first) {
if(*p == c) {
return p;
}
p--;
}
return NULL;
}
static ngx_inline uint32_t
ngx_inet_aton(u_char *data, ngx_uint_t len)
{
long long result = 0;
long long temp = 0;
u_char *last = data + len;
int point = 0;
while(data <= last) {
if(*data == '.' || data == last) {
if(temp > 255) {
return NGX_ERROR;
}
result = (result << 8) + temp;
temp = 0;
++point;
if(point == 4) {
break;
}
} else if(*data <= '9' && *data >= '0') {
temp = temp * 10 + (*data - '0');
} else {
return NGX_ERROR;
}
++data;
}
if(point != 4) {
return NGX_ERROR;
}
return result;
}
ngx_int_t
ngx_ip2region_search(ngx_str_t *addr_text, ngx_str_t *isp, ngx_str_t *city)
{
if(g_ip2region_entry.dbHandler == NULL) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "search error ip %V, ip2region doesn't create", addr_text);
return NGX_ERROR;
}
uint32_t addr_binary = ngx_inet_aton(addr_text->data, addr_text->len);
if(addr_binary == (uint32_t)NGX_ERROR) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "search error ip %V: bad ip address", addr_text);
return NGX_ERROR;
}
datablock_entry datablock;
ngx_memzero(&datablock, sizeof(datablock));
uint_t rc = ip2region_search_func(&g_ip2region_entry, (uint_t)addr_binary, &datablock);
if(!rc) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "%V search failed", addr_text);
return NGX_ERROR;
}
ngx_log_debug2(NGX_LOG_INFO, ngx_cycle->log, 0, "%V: %s", addr_text, datablock.region);
//城市Id 国家|区域|省份|城市|ISP
u_char *end = (u_char *)(datablock.region + ngx_strlen(datablock.region));
u_char *pos = ngx_strrchr((u_char *)datablock.region, end, '|');
if(!pos) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "search isp failed");
return NGX_ERROR;
}
u_char isp_buffer[64] = {0};
ngx_snprintf(isp_buffer, sizeof(isp_buffer), "%*s%Z", end - pos, pos + 1);
ngx_log_debug3(NGX_LOG_INFO, ngx_cycle->log, 0, "%V: %s [%s]", addr_text, datablock.region, (char *)isp_buffer);
if(city) {
end = pos - 1;
u_char *pos_city = ngx_strrchr((u_char *)datablock.region, end, '|');
if(!pos_city) {
ngx_log_debug0(NGX_LOG_ERR, ngx_cycle->log, 0, "search city failed");
return NGX_ERROR;
}
u_char city_buffer[64] = {0};
ngx_snprintf(city_buffer, sizeof(city_buffer), "%*s%Z", end - pos_city, pos_city + 1);
}
return NGX_OK;
}

View File

@ -1,2 +0,0 @@
node_modules/
data/

View File

@ -1,4 +0,0 @@
{
"singleQuote": true,
"tabWidth": 4
}

View File

@ -1,103 +0,0 @@
# nodejs 客户端
官方维护的 ip2region, 每次数据更新后会更新到 npm
## Install
**node 版本 : >= 6.0.0**
```
npm install node-ip2region --save
```
## 已测试通过的 node 版本列表
```
6.0.0
6.11.2
8.0.0
10.0.0
12.0.0
```
## Example
```
const searcher = require('node-ip2region').create();
searcher.btreeSearchSync('xxx.xxx.xxx.xxx')
// => { city: 2163, region: '中国|0|广东省|深圳市|联通' }
```
## 实现情况:
现已实现同步和异步查询,具体使用方法可以参考 `nodejs\tests\constructorTest.spec.js``nodejs\tests\createTest.spec.js`
## 如何贡献?
你可以任意修改代码,但必须确保通过全部的单元测试。要保证通过全部的单元测试,请在 Nodejs 控制台下切换到 nodejs 目录:
1在此之前请先运行 `npm i` 确保你已经安装了各类初始化第三方工具。
2然后运行 `npm run coverage` 确保你的代码可以通过全部测试(必要时可以添加测试)。
```bash
D:\Projects\ip2region\binding\nodejs>npm run coverage
> ip2region@0.0.1 coverage D:\Projects\ip2region\binding\nodejs
> npm run test && jest --coverage
> ip2region@0.0.1 test D:\Projects\ip2region\binding\nodejs
> jest
PASS tests\constructorTest.spec.js
PASS tests\createTest.spec.js
PASS tests\exceptionTest.spec.js
Snapshot Summary
168 snapshots written in 2 test suites.
Test Suites: 3 passed, 3 total
Tests: 14 passed, 14 total
Snapshots: 168 added, 168 total
Time: 1.645s
Ran all test suites.
PASS tests\constructorTest.spec.js
PASS tests\createTest.spec.js
PASS tests\exceptionTest.spec.js
----------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------------|----------|----------|----------|----------|-------------------|
All files | 92.34 | 80.77 | 96 | 93.83 | |
nodejs | 91.95 | 80.26 | 95.65 | 93.51 | |
ip2region.js | 91.95 | 80.26 | 95.65 | 93.51 |... 09,410,460,484 |
nodejs/tests/utils | 100 | 100 | 100 | 100 | |
asyncFor.js | 100 | 100 | 100 | 100 | |
fetchMainVersion.js | 100 | 100 | 100 | 100 | |
testData.js | 100 | 100 | 100 | 100 | |
----------------------|----------|----------|----------|----------|-------------------|
Test Suites: 3 passed, 3 total
Tests: 14 passed, 14 total
Snapshots: 168 passed, 168 total
Time: 1.792s
Ran all test suites.
```
3使用benchmark测试结果如下
```bash
D:\Projects\ip2region\binding\nodejs>node D:\Projects\ip2region\binding\nodejs\tests\benchmarkTests\main.js
MemorySearchSync x 55,969 ops/sec ±2.22% (90 runs sampled)
BinarySearchSync x 610 ops/sec ±5.41% (77 runs sampled)
BtreeSearchSync x 2,439 ops/sec ±6.93% (69 runs sampled)
MemorySearch x 2,924 ops/sec ±0.67% (85 runs sampled)
BinarySearch x 154 ops/sec ±2.20% (69 runs sampled)
BtreeSearch x 294 ops/sec ±2.58% (76 runs sampled)
Rand Name Time (in milliseconds)
1 MemorySearchSync 0.018
2 MemorySearch 0.342
3 BtreeSearchSync 0.410
4 BinarySearchSync 1.639
5 BtreeSearch 3.407
6 BinarySearch 6.497
```

View File

@ -1,11 +0,0 @@
#!/bin/sh
echo 'create dir'
if [ ! -d "data" ]; then
mkdir data
fi
echo "copy db"
cp '../../data/ip2region.db' './data/'
echo "npm publish"
npm publish

View File

@ -1,634 +0,0 @@
/**
* ip2region client for nodejs
*
* project: https://github.com/lionsoul2014/ip2region
*
* @author dongyado<dongyado@gmail.com>
* @author leeching<leeching.fx@gmail.com>
* @author dongwei<maledong_github@outlook.com>
*/
const fs = require('fs');
const path = require('path');
const DEFAULT_DB_PATH = path.join(__dirname,'./data/ip2region.db') ;
//#region Private Functions
/**
* Convert ip to long (xxx.xxx.xxx.xxx to a integer)
*
* @param {string} ip
* @return {number} long value
*/
function _ip2long(ip) {
const arr = ip.split('.');
if (arr.length !== 4) {
throw new Error('invalid ip');
}
return arr.reduce((val, n, i) => {
n = Number(n);
if (!Number.isInteger(n) || n < 0 || n > 255) {
throw new Error('invalid ip');
}
return val + IP_BASE[i] * n;
}, 0);
}
/**
* Get long value from buffer with specified offset
*
* @param {Buffer} buffer
* @param {number} offset
* @return {number} long value
*/
function _getLong(buffer, offset) {
const val =
(buffer[offset] & 0x000000ff) |
((buffer[offset + 1] << 8) & 0x0000ff00) |
((buffer[offset + 2] << 16) & 0x00ff0000) |
((buffer[offset + 3] << 24) & 0xff000000);
return val < 0 ? val >>> 0 : val;
}
//#endregion
//#region Private Variables
// We don't wanna expose a private global settings to
// the public for safety reason.
const _globalInstances = new Map();
const IP_BASE = [16777216, 65536, 256, 1];
const INDEX_BLOCK_LENGTH = 12;
const TOTAL_HEADER_LENGTH = 8192;
// Private Message Symbols for functions
const PrepareHeader = Symbol('#PrepareHeader');
const CalTotalBlocks = Symbol('#CalsTotalBlocks');
const ReadDataSync = Symbol('#ReadDataSync');
const ReadData = Symbol('#ReadData');
//#endregion
class IP2Region {
//#region Private Functions
[CalTotalBlocks]() {
const superBlock = Buffer.alloc(8);
fs.readSync(this.dbFd, superBlock, 0, 8, 0);
this.firstIndexPtr = _getLong(superBlock, 0);
this.lastIndexPtr = _getLong(superBlock, 4);
this.totalBlocks =
(this.lastIndexPtr - this.firstIndexPtr) / INDEX_BLOCK_LENGTH + 1;
}
[PrepareHeader]() {
fs.readSync(
this.dbFd,
this.headerIndexBuffer,
0,
TOTAL_HEADER_LENGTH,
8
);
for (let i = 0; i < TOTAL_HEADER_LENGTH; i += 8) {
const startIp = _getLong(this.headerIndexBuffer, i);
const dataPtr = _getLong(this.headerIndexBuffer, i + 4);
if (dataPtr == 0) break;
this.headerSip.push(startIp);
this.headerPtr.push(dataPtr);
this.headerLen++; // header index size count
}
}
[ReadData](dataPos, callBack) {
if (dataPos == 0) return callBack(null, null);
const dataLen = (dataPos >> 24) & 0xff;
dataPos = dataPos & 0x00ffffff;
const dataBuffer = Buffer.alloc(dataLen);
fs.read(this.dbFd, dataBuffer, 0, dataLen, dataPos, (err, result) => {
if (err) {
callBack(err, null);
}
else {
const city = _getLong(dataBuffer, 0);
const region = dataBuffer.toString('utf8', 4, dataLen);
callBack(null, { city, region });
}
});
}
[ReadDataSync](dataPos) {
if (dataPos == 0) return null;
const dataLen = (dataPos >> 24) & 0xff;
dataPos = dataPos & 0x00ffffff;
const dataBuffer = Buffer.alloc(dataLen);
fs.readSync(this.dbFd, dataBuffer, 0, dataLen, dataPos);
const city = _getLong(dataBuffer, 0);
const region = dataBuffer.toString('utf8', 4, dataLen);
return { city, region };
}
//#endregion
//#region Static Functions
// Single Instance
static create(dbPath = DEFAULT_DB_PATH) {
let existInstance = _globalInstances.get(dbPath);
if (existInstance == null) {
existInstance = new IP2Region({ dbPath: dbPath });
}
return existInstance;
}
/**
* For backward compatibility
*/
static destroy() {
_globalInstances.forEach(([key, instance]) => {
instance.destroy();
});
}
//#endregion
constructor(options = {}) {
const { dbPath } = options;
// Keep for MemorySearch
this.totalInMemoryBytesSize = fs.statSync(dbPath).size;
this.totalInMemoryBytes = null;
this.dbFd = fs.openSync(dbPath, 'r');
this.dbPath = dbPath;
_globalInstances.set(this.dbPath, this);
this.totalBlocks = this.firstIndexPtr = this.lastIndexPtr = 0;
this[CalTotalBlocks]();
this.headerIndexBuffer = Buffer.alloc(TOTAL_HEADER_LENGTH);
this.headerSip = [];
this.headerPtr = [];
this.headerLen = 0;
this[PrepareHeader]();
}
//#region Public Functions
/**
* Destroy the current file by closing it.
*/
destroy() {
fs.closeSync(this.dbFd);
_globalInstances.delete(this.dbPath);
}
/**
* Sync of binarySearch.
* @param {string} ip The IP address to search for.
* @return {SearchResult} A result something like `{ city: 2163, region: '中国|0|广东省|深圳市|阿里云' }`
*/
binarySearchSync(ip) {
ip = _ip2long(ip);
let low = 0;
let mid = 0;
let high = this.totalBlocks;
let pos = 0;
let sip = 0;
const indexBuffer = Buffer.alloc(12);
// binary search
while (low <= high) {
mid = (low + high) >> 1;
pos = this.firstIndexPtr + mid * INDEX_BLOCK_LENGTH;
fs.readSync(this.dbFd, indexBuffer, 0, INDEX_BLOCK_LENGTH, pos);
sip = _getLong(indexBuffer, 0);
if (ip < sip) {
high = mid - 1;
} else {
sip = _getLong(indexBuffer, 4);
if (ip > sip) {
low = mid + 1;
} else {
sip = _getLong(indexBuffer, 8);
break;
}
}
}
return this[ReadDataSync](sip);
}
/**
* Async of binarySearch.
* @param {string} ip The IP address to search for.
* @param {Function} callBack The callBack function with two parameters, if successful,
* err is null and result is `{ city: 2163, region: '中国|0|广东省|深圳市|阿里云' }`
*/
binarySearch(ip, callBack) {
ip = _ip2long(ip);
let low = 0;
let mid = 0;
let high = this.totalBlocks;
let pos = 0;
let sip = 0;
const indexBuffer = Buffer.alloc(12);
const _self = this;
// Because `while` is a sync method, we have to convert this to a recursive loop
// and in each loop we should continue calling `setImmediate` until we found the IP.
function _innerAsyncWhile() {
if (low <= high) {
mid = (low + high) >> 1;
pos = _self.firstIndexPtr + mid * INDEX_BLOCK_LENGTH;
// Now async read the file
fs.read(_self.dbFd, indexBuffer, 0, INDEX_BLOCK_LENGTH, pos, (err) => {
if (err) {
return callBack(err, null);
}
sip = _getLong(indexBuffer, 0);
if (ip < sip) {
high = mid - 1;
setImmediate(_innerAsyncWhile);
} else {
sip = _getLong(indexBuffer, 4);
if (ip > sip) {
low = mid + 1;
setImmediate(_innerAsyncWhile);
} else {
sip = _getLong(indexBuffer, 8);
_self[ReadData](sip, (err, result) => {
callBack(err, result);
});
}
}
});
}
}
// Call this immediately
_innerAsyncWhile();
}
/**
* Sync of btreeSearch.
* @param {string} ip The IP address to search for.
* @return {Function} A result something like `{ city: 2163, region: '中国|0|广东省|深圳市|阿里云' }`
*/
btreeSearchSync(ip) {
ip = _ip2long(ip);
// first search (in header index)
let low = 0;
let mid = 0;
let high = this.headerLen;
let sptr = 0;
let eptr = 0;
while (low <= high) {
mid = (low + high) >> 1;
if (ip == this.headerSip[mid]) {
if (mid > 0) {
sptr = this.headerPtr[mid - 1];
eptr = this.headerPtr[mid];
} else {
sptr = this.headerPtr[mid];
eptr = this.headerPtr[mid + 1];
}
break;
}
if (ip < this.headerSip[mid]) {
if (mid == 0) {
sptr = this.headerPtr[mid];
eptr = this.headerPtr[mid + 1];
break;
} else if (ip > this.headerSip[mid - 1]) {
sptr = this.headerPtr[mid - 1];
eptr = this.headerPtr[mid];
break;
}
high = mid - 1;
} else {
if (mid == this.headerLen - 1) {
sptr = this.headerPtr[mid - 1];
eptr = this.headerPtr[mid];
break;
} else if (ip <= this.headerSip[mid + 1]) {
sptr = this.headerPtr[mid];
eptr = this.headerPtr[mid + 1];
break;
}
low = mid + 1;
}
}
// match nothing
if (sptr == 0) return null;
// second search (in index)
const blockLen = eptr - sptr;
const blockBuffer = Buffer.alloc(blockLen + INDEX_BLOCK_LENGTH);
fs.readSync(
this.dbFd,
blockBuffer,
0,
blockLen + INDEX_BLOCK_LENGTH,
sptr
);
low = 0;
high = blockLen / INDEX_BLOCK_LENGTH;
let p = 0;
let sip = 0;
while (low <= high) {
mid = (low + high) >> 1;
p = mid * INDEX_BLOCK_LENGTH;
sip = _getLong(blockBuffer, p);
if (ip < sip) {
high = mid - 1;
} else {
sip = _getLong(blockBuffer, p + 4);
if (ip > sip) {
low = mid + 1;
} else {
sip = _getLong(blockBuffer, p + 8);
break;
}
}
}
return this[ReadDataSync](sip);
}
/**
* Async of btreeSearch.
* @param {string} ip The IP address to search for.
* @param {Function} callBack The callBack function with two parameters, if successful,
* err is null and result is `{ city: 2163, region: '中国|0|广东省|深圳市|阿里云' }`
*/
btreeSearch(ip, callBack) {
ip = _ip2long(ip);
// first search (in header index)
let low = 0;
let mid = 0;
let high = this.headerLen;
let sptr = 0;
let eptr = 0;
while (low <= high) {
mid = (low + high) >> 1;
if (ip == this.headerSip[mid]) {
if (mid > 0) {
sptr = this.headerPtr[mid - 1];
eptr = this.headerPtr[mid];
} else {
sptr = this.headerPtr[mid];
eptr = this.headerPtr[mid + 1];
}
break;
}
if (ip < this.headerSip[mid]) {
if (mid == 0) {
sptr = this.headerPtr[mid];
eptr = this.headerPtr[mid + 1];
break;
} else if (ip > this.headerSip[mid - 1]) {
sptr = this.headerPtr[mid - 1];
eptr = this.headerPtr[mid];
break;
}
high = mid - 1;
} else {
if (mid == this.headerLen - 1) {
sptr = this.headerPtr[mid - 1];
eptr = this.headerPtr[mid];
break;
} else if (ip <= this.headerSip[mid + 1]) {
sptr = this.headerPtr[mid];
eptr = this.headerPtr[mid + 1];
break;
}
low = mid + 1;
}
}
// match nothing
if (sptr == 0) return callBack(null, null);
let p = 0;
let sip = 0;
// second search (in index)
const blockLen = eptr - sptr;
const blockBuffer = Buffer.alloc(blockLen + INDEX_BLOCK_LENGTH);
low = 0;
high = blockLen / INDEX_BLOCK_LENGTH;
const _self = this;
function _innerAsyncWhile() {
if (low <= high) {
mid = (low + high) >> 1;
p = mid * INDEX_BLOCK_LENGTH;
// Use this to call the method itself as
// an asynchronize step
fs.read(_self.dbFd, blockBuffer,
0,
blockLen + INDEX_BLOCK_LENGTH,
sptr, (err) => {
if (err) {
return callBack(err, null);
}
sip = _getLong(blockBuffer, p);
if (ip < sip) {
high = mid - 1;
setImmediate(_innerAsyncWhile);
} else {
sip = _getLong(blockBuffer, p + 4);
if (ip > sip) {
low = mid + 1;
setImmediate(_innerAsyncWhile);
} else {
sip = _getLong(blockBuffer, p + 8);
_self[ReadData](sip, (err, result) => {
callBack(err, result);
});
}
}
});
}
else {
// If we found nothing, return null
return callBack(null, null);
}
}
_innerAsyncWhile();
}
/**
* Sync of MemorySearch.
* @param {String} ip
*/
memorySearchSync(ip) {
ip = _ip2long(ip);
if (this.totalInMemoryBytes === null) {
this.totalInMemoryBytes = Buffer.alloc(this.totalInMemoryBytesSize);
fs.readSync(this.dbFd, this.totalInMemoryBytes, 0, this.totalInMemoryBytesSize, 0);
this.firstIndexPtr = _getLong(this.totalInMemoryBytes, 0);
this.lastIndexPtr = _getLong(this.totalInMemoryBytes, 4);
this.totalBlocks = ((this.lastIndexPtr - this.firstIndexPtr) / INDEX_BLOCK_LENGTH) | 0 + 1;
}
let l = 0, h = this.totalBlocks;
let sip = 0;
let m = 0, p = 0;
while (l <= h) {
m = (l + h) >> 1;
p = (this.firstIndexPtr + m * INDEX_BLOCK_LENGTH) | 0;
sip = _getLong(this.totalInMemoryBytes, p);
if (ip < sip) {
h = m - 1;
}
else {
sip = _getLong(this.totalInMemoryBytes, p + 4);
if (ip > sip) {
l = m + 1;
}
else {
sip = _getLong(this.totalInMemoryBytes, p + 8);
//not matched
if (sip === 0) return null;
//get the data
let dataLen = ((sip >> 24) & 0xFF) | 0;
let dataPtr = ((sip & 0x00FFFFFF)) | 0;
let city = _getLong(this.totalInMemoryBytes, dataPtr);
const bufArray = new Array();
for (let startPos = dataPtr + 4, i = startPos; i < startPos + dataLen - 4; ++i) {
bufArray.push(this.totalInMemoryBytes[i]);
}
const region = Buffer.from(bufArray, 0).toString();
return { city, region };
}
}
}
}
/**
* Async of MemorySearch.
* @param {String} ip
*/
memorySearch(ip, callBack) {
let _ip = _ip2long(ip);
let l = 0, h = this.totalBlocks;
let sip = 0;
let m = 0, p = 0;
let self = this;
function _innerMemorySearchLoop() {
if (l <= h) {
m = (l + h) >> 1;
p = (self.firstIndexPtr + m * INDEX_BLOCK_LENGTH) | 0;
sip = _getLong(self.totalInMemoryBytes, p);
if (_ip < sip) {
h = m - 1;
setImmediate(_innerMemorySearchLoop);
}
else {
sip = _getLong(self.totalInMemoryBytes, p + 4);
if (_ip > sip) {
l = m + 1;
setImmediate(_innerMemorySearchLoop);
}
else {
sip = _getLong(self.totalInMemoryBytes, p + 8);
//not matched
if (sip === 0) return callBack(null, null);
//get the data
let dataLen = ((sip >> 24) & 0xFF) | 0;
let dataPtr = ((sip & 0x00FFFFFF)) | 0;
let city = _getLong(self.totalInMemoryBytes, dataPtr);
const bufArray = new Array();
for (let startPos = dataPtr + 4, i = startPos; i < startPos + dataLen - 4; ++i) {
bufArray.push(self.totalInMemoryBytes[i]);
}
const region = Buffer.from(bufArray).toString();
callBack(null, { city, region });
}
}
}
else {
callBack(null, null);
}
}
if (this.totalInMemoryBytes === null) {
this.totalInMemoryBytes = Buffer.alloc(this.totalInMemoryBytesSize);
fs.read(this.dbFd, this.totalInMemoryBytes, 0, this.totalInMemoryBytesSize, 0, (err) => {
if (err) {
callBack(err, null);
}
else {
this.firstIndexPtr = _getLong(this.totalInMemoryBytes, 0);
this.lastIndexPtr = _getLong(this.totalInMemoryBytes, 4);
this.totalBlocks = ((this.lastIndexPtr - this.firstIndexPtr) / INDEX_BLOCK_LENGTH) | 0 + 1;
_innerMemorySearchLoop();
}
});
}
else {
_innerMemorySearchLoop();
}
}
}
//#endregion
module.exports = IP2Region;

File diff suppressed because it is too large Load Diff

View File

@ -1,33 +0,0 @@
{
"name": "node-ip2region",
"version": "1.0.2",
"description": "official nodejs client of ip2region",
"main": "ip2region.js",
"scripts": {
"test": "jest",
"coverage": "npm run test && jest --coverage"
},
"files": ["data/"],
"repository": {
"type": "git",
"url": "https://github.com/lionsoul2014/ip2region"
},
"keywords": [
"ip2region",
"ip",
"region"
],
"author": "dongyado",
"license": "ISC",
"bugs": {
"url": "https://github.com/lionsoul2014/ip2region/issues"
},
"homepage": "https://github.com/lionsoul2014/ip2region",
"devDependencies": {
"jest": "^19.0.2",
"benchmark": "^2.1.4"
},
"engines": {
"node" : ">=6.0.0"
}
}

View File

@ -1,94 +0,0 @@
const Benchmark = require('benchmark');
const suite = new Benchmark.Suite();
const searcher = require('../../ip2region').create('../../data/ip2region.db');
const testDatas = require('../utils/testData');
const asyncFor = require('../utils/asyncFor');
suite.add("MemorySearchSync", () => {
for (let i = 0; i < testDatas.length; ++i) {
searcher.memorySearchSync(testDatas[i]);
}
})
.add("BinarySearchSync", () => {
for (let i = 0; i < testDatas.length; ++i) {
searcher.binarySearchSync(testDatas[i]);
}
})
.add("BtreeSearchSync", () => {
for (let i = 0; i < testDatas.length; ++i) {
searcher.btreeSearchSync(testDatas[i]);
}
})
.add("MemorySearch", {
defer: true,
fn: function (completeCallBack) {
asyncFor(testDatas,
(v, c) => {
searcher.memorySearch(v, () => {
c();
});
},
() => {
completeCallBack.resolve();
});
}
})
.add("BinarySearch", {
defer: true,
fn: function (completeCallBack) {
asyncFor(testDatas,
(v, c) => {
searcher.binarySearch(v, () => {
c();
});
},
() => {
completeCallBack.resolve();
});
}
})
.add("BtreeSearch", {
defer: true,
fn: function (completeCallBack) {
asyncFor(testDatas,
(v, c) => {
searcher.btreeSearch(v, () => {
c();
});
},
() => {
completeCallBack.resolve();
});
}
})
.on('cycle', function (event) {
console.log(String(event.target));
})
.on('complete', function () {
let results = new Array();
for (let prop in this) {
if (!isNaN(prop)) {
const eachResult = {
name: this[prop].name,
mean: this[prop].stats.mean * 1000, //second => millisecond
moe: this[prop].stats.moe,
rme: this[prop].stats.rme,
sem: this[prop].stats.sem
}
results.push(eachResult);
}
}
results = results.sort((a, b) => { return a.mean - b.mean });
console.log(`Rand\t${'Name'.padEnd(20)}Time (in milliseconds)`);
let id = 1;
for (let r of results) {
console.log(`${id++}\t${r.name.padEnd(20)}${r.mean.toFixed(3)}`);
}
})
.run({ async: true });

View File

@ -1,145 +0,0 @@
// This test is used for tesing of a static function `create` of IP2Region
const IP2Region = require('../../ip2region');
const testIps = require('../utils/testData');
const asyncFor = require('../utils/asyncFor');
describe('Constructor Test', () => {
let instance;
beforeAll(() => {
instance = new IP2Region({ dbPath: '../../data/ip2region.db' });
});
afterAll(() => {
IP2Region.destroy();
});
test('btreeSearchSync query', () => {
for (const ip of testIps) {
expect(instance.btreeSearchSync(ip)).toMatchSnapshot();
}
});
test('binarySearchSync query', () => {
for (const ip of testIps) {
expect(instance.binarySearchSync(ip)).toMatchSnapshot();
}
});
test('memorySearchSync query', () => {
for (const ip of testIps) {
expect(instance.memorySearchSync(ip)).toMatchSnapshot();
}
});
//#region callBack
test('binarySearch query', (done) => {
asyncFor(testIps,
(value, continueCallBack) => {
instance.binarySearch(value, (err, result) => {
expect(err).toBe(null);
expect(result).toMatchSnapshot();
continueCallBack();
});
},
() => { done() });
});
test('btreeSearch query', (done) => {
asyncFor(testIps,
(value, continueCallBack) => {
instance.btreeSearch(value, (err, result) => {
expect(err).toBe(null);
expect(result).toMatchSnapshot();
continueCallBack();
});
},
() => { done() });
});
test('memorySearch query', (done) => {
asyncFor(testIps,
(value, continueCallBack) => {
instance.memorySearch(value, (err, result) => {
expect(err).toBe(null);
expect(result).toMatchSnapshot();
continueCallBack();
});
},
() => { done() });
});
//#endregion
//#region Async Promisify test
const node_ver = require('../utils/fetchMainVersion');
// If we have Nodejs >= 8, we now support `async` and `await`
if (node_ver >= 8) {
const asyncBinarySearch = async (ip) => {
return new Promise((resolve, reject) => {
instance.binarySearch(ip, (err, result) => {
if (err) {
reject(err);
}
else {
resolve(result);
}
});
});
};
const asyncBtreeSearch = async (ip) => {
return new Promise((resolve, reject) => {
instance.btreeSearch(ip, (err, result) => {
if (err) {
reject(err);
}
else {
resolve(result);
}
});
});
};
const asyncMemorySearch = async (ip) => {
return new Promise((succ, fail) => {
instance.memorySearch(ip, (err, result) => {
if (err) {
fail(err);
}
else {
succ(result);
}
});
});
}
test('async binarySearch query', async () => {
for (let i = 0; i < testIps.length; ++i) {
const result = await asyncBinarySearch(testIps[i]);
expect(result).toMatchSnapshot();
}
});
test('async btreeSearch query', async () => {
for (let i = 0; i < testIps.length; ++i) {
const result = await asyncBtreeSearch(testIps[i]);
expect(result).toMatchSnapshot();
}
});
test('async memorySearch query', async () => {
for (let i = 0; i < testIps.length; ++i) {
const result = await asyncMemorySearch(testIps[i]);
expect(result).toMatchSnapshot();
}
});
}
//#endregion
});

View File

@ -1,146 +0,0 @@
// This test is used for tesing of a static function `create` of IP2Region
const IP2Region = require('../../ip2region');
const testIps = require('../utils/testData');
const asyncFor = require('../utils/asyncFor');
describe('Create Test', () => {
let instance;
beforeAll(() => {
instance = IP2Region.create('../../data/ip2region.db');
});
afterAll(() => {
IP2Region.destroy();
});
test('btreeSearchSync query', () => {
for (const ip of testIps) {
expect(instance.btreeSearchSync(ip)).toMatchSnapshot();
}
});
test('binarySearchSync query', () => {
for (const ip of testIps) {
expect(instance.binarySearchSync(ip)).toMatchSnapshot();
}
});
test('memorySearchSync query', () => {
for (const ip of testIps) {
expect(instance.memorySearchSync(ip)).toMatchSnapshot();
}
});
//#region callBack
test('binarySearch query', (done) => {
asyncFor(testIps,
(value, continueCallBack) => {
instance.binarySearch(value, (err, result) => {
expect(err).toBe(null);
expect(result).toMatchSnapshot();
continueCallBack();
});
},
() => { done() });
});
test('btreeSearch query', (done) => {
asyncFor(testIps,
(value, continueCallBack) => {
instance.btreeSearch(value, (err, result) => {
expect(err).toBe(null);
expect(result).toMatchSnapshot();
continueCallBack();
});
},
() => { done() });
});
test('memorySearch query', (done) => {
asyncFor(testIps,
(value, continueCallBack) => {
instance.memorySearch(value, (err, result) => {
expect(err).toBe(null);
expect(result).toMatchSnapshot();
continueCallBack();
});
},
() => { done() });
});
//#endregion
//#region Async Promisify test
const node_ver = require('../utils/fetchMainVersion');
// If we have Nodejs >= 8, we now support `async` and `await`
if (node_ver >= 8) {
const asyncBinarySearch = async (ip) => {
return new Promise((resolve, reject) => {
instance.binarySearch(ip, (err, result) => {
if (err) {
reject(err);
}
else {
resolve(result);
}
});
});
};
const asyncBtreeSearch = async (ip) => {
return new Promise((resolve, reject) => {
instance.btreeSearch(ip, (err, result) => {
if (err) {
reject(err);
}
else {
resolve(result);
}
});
});
};
const asyncMemorySearch = async (ip) => {
return new Promise((succ, fail) => {
instance.memorySearch(ip, (err, result) => {
if (err) {
fail(err);
}
else {
succ(result);
}
});
});
}
test('async binarySearch query', async () => {
for (let i = 0; i < testIps.length; ++i) {
const result = await asyncBinarySearch(testIps[i]);
expect(result).toMatchSnapshot();
}
});
test('async btreeSearch query', async () => {
for (let i = 0; i < testIps.length; ++i) {
const result = await asyncBtreeSearch(testIps[i]);
expect(result).toMatchSnapshot();
}
});
test('async memorySearch query', async () => {
for (let i = 0; i < testIps.length; ++i) {
const result = await asyncMemorySearch(testIps[i]);
expect(result).toMatchSnapshot();
}
});
}
//#endregion
});

View File

@ -1,28 +0,0 @@
// This test is used for tesing of exceptions
const IP2Region = require('../../ip2region');
describe('Constructor Test', () => {
let instance;
beforeAll(() => {
instance = new IP2Region({ dbPath: '../../data/ip2region.db' })
});
afterAll(() => {
instance.destroy();
});
test('IP invalid test', () => {
const invalidIps = ['255.234.233', '255.255.-1.255', null, undefined, '', 'x.255.y.200'];
for (const ip of invalidIps) {
expect(() => instance.btreeSearchSync(ip)).toThrow();
expect(() => instance.binarySearchSync(ip)).toThrow();
}
});
test('File Not Found test', () => {
expect(() => new IP2Region({ dbPath: 'A Bad File or Path Here' })).toThrow();
});
});

View File

@ -1,23 +0,0 @@
/**
* Async For
* @param {Array} groupArray
* @param {Function} exeCallBack
* @param {Function} finalCallBack
*/
function asyncFor(groupArray, exeCallBack, finalCallBack) {
let i = 0;
function _innerAsyncLoop() {
if (i < groupArray.length) {
exeCallBack(groupArray[i++], _innerAsyncLoop);
}
else {
finalCallBack();
}
}
_innerAsyncLoop();
}
module.exports = asyncFor;

View File

@ -1,9 +0,0 @@
let node_ver = process.version
// Because nodejs's version is something like `v8.11.3`. So we should ignore `v` first
node_ver = node_ver.substr(1);
// Splitted by `.`
node_ver = node_ver.split('.');
// Take the main version number
node_ver = parseInt(node_ver[0]);
module.exports = node_ver;

View File

@ -1,16 +0,0 @@
module.exports = [
'0.0.0.0',
'10.10.10.10',
'210.109.255.230',
'192.168.0.1',
'255.255.255.255',
'77.49.66.88',
'210.248.255.231',
'35.193.251.120',
'197.84.60.202',
'183.196.233.159',
'20.108.91.101',
'120.196.148.137',
'249.255.250.200',
'112.65.1.130'
]

File diff suppressed because it is too large Load Diff

View File

@ -1,360 +0,0 @@
<?php
/**
* ip2region php seacher client class
*
* @author chenxin<chenxin619315@gmail.com>
* @date 2015-10-29
*/
defined('INDEX_BLOCK_LENGTH') or define('INDEX_BLOCK_LENGTH', 12);
defined('TOTAL_HEADER_LENGTH') or define('TOTAL_HEADER_LENGTH', 8192);
class Ip2Region
{
/**
* db file handler
*/
private $dbFileHandler = NULL;
/**
* header block info
*/
private $HeaderSip = NULL;
private $HeaderPtr = NULL;
private $headerLen = 0;
/**
* super block index info
*/
private $firstIndexPtr = 0;
private $lastIndexPtr = 0;
private $totalBlocks = 0;
/**
* for memory mode only
* the original db binary string
*/
private $dbBinStr = NULL;
private $dbFile = NULL;
/**
* construct method
*
* @param ip2regionFile
*/
public function __construct( $ip2regionFile)
{
$this->dbFile = $ip2regionFile;
}
/**
* all the db binary string will be loaded into memory
* then search the memory only and this will a lot faster than disk base search
* @Note:
* invoke it once before put it to public invoke could make it thread safe
*
* @param $ip
*/
public function memorySearch($ip)
{
//check and load the binary string for the first time
if ( $this->dbBinStr == NULL ) {
$this->dbBinStr = file_get_contents($this->dbFile);
if ( $this->dbBinStr == false ) {
throw new Exception("Fail to open the db file {$this->dbFile}");
}
$this->firstIndexPtr = self::getLong($this->dbBinStr, 0);
$this->lastIndexPtr = self::getLong($this->dbBinStr, 4);
$this->totalBlocks = ($this->lastIndexPtr-$this->firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
}
if ( is_string($ip) ) $ip = self::safeIp2long($ip);
//binary search to define the data
$l = 0;
$h = $this->totalBlocks;
$dataPtr = 0;
while ( $l <= $h ) {
$m = (($l + $h) >> 1);
$p = $this->firstIndexPtr + $m * INDEX_BLOCK_LENGTH;
$sip = self::getLong($this->dbBinStr, $p);
if ( $ip < $sip ) {
$h = $m - 1;
} else {
$eip = self::getLong($this->dbBinStr, $p + 4);
if ( $ip > $eip ) {
$l = $m + 1;
} else {
$dataPtr = self::getLong($this->dbBinStr, $p + 8);
break;
}
}
}
//not matched just stop it here
if ( $dataPtr == 0 ) return NULL;
//get the data
$dataLen = (($dataPtr >> 24) & 0xFF);
$dataPtr = ($dataPtr & 0x00FFFFFF);
return array(
'city_id' => self::getLong($this->dbBinStr, $dataPtr),
'region' => substr($this->dbBinStr, $dataPtr + 4, $dataLen - 4)
);
}
/**
* get the data block through the specified ip address or long ip numeric with binary search algorithm
*
* @param ip
* @return mixed Array or NULL for any error
*/
public function binarySearch( $ip )
{
//check and conver the ip address
if ( is_string($ip) ) $ip = self::safeIp2long($ip);
if ( $this->totalBlocks == 0 ) {
//check and open the original db file
if ( $this->dbFileHandler == NULL ) {
$this->dbFileHandler = fopen($this->dbFile, 'r');
if ( $this->dbFileHandler == false ) {
throw new Exception("Fail to open the db file {$this->dbFile}");
}
}
fseek($this->dbFileHandler, 0);
$superBlock = fread($this->dbFileHandler, 8);
$this->firstIndexPtr = self::getLong($superBlock, 0);
$this->lastIndexPtr = self::getLong($superBlock, 4);
$this->totalBlocks = ($this->lastIndexPtr-$this->firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
}
//binary search to define the data
$l = 0;
$h = $this->totalBlocks;
$dataPtr = 0;
while ( $l <= $h ) {
$m = (($l + $h) >> 1);
$p = $m * INDEX_BLOCK_LENGTH;
fseek($this->dbFileHandler, $this->firstIndexPtr + $p);
$buffer = fread($this->dbFileHandler, INDEX_BLOCK_LENGTH);
$sip = self::getLong($buffer, 0);
if ( $ip < $sip ) {
$h = $m - 1;
} else {
$eip = self::getLong($buffer, 4);
if ( $ip > $eip ) {
$l = $m + 1;
} else {
$dataPtr = self::getLong($buffer, 8);
break;
}
}
}
//not matched just stop it here
if ( $dataPtr == 0 ) return NULL;
//get the data
$dataLen = (($dataPtr >> 24) & 0xFF);
$dataPtr = ($dataPtr & 0x00FFFFFF);
fseek($this->dbFileHandler, $dataPtr);
$data = fread($this->dbFileHandler, $dataLen);
return array(
'city_id' => self::getLong($data, 0),
'region' => substr($data, 4)
);
}
/**
* get the data block associated with the specified ip with b-tree search algorithm
* @Note: not thread safe
*
* @param ip
* @return Mixed Array for NULL for any error
*/
public function btreeSearch( $ip )
{
if ( is_string($ip) ) $ip = self::safeIp2long($ip);
//check and load the header
if ( $this->HeaderSip == NULL ) {
//check and open the original db file
if ( $this->dbFileHandler == NULL ) {
$this->dbFileHandler = fopen($this->dbFile, 'r');
if ( $this->dbFileHandler == false ) {
throw new Exception("Fail to open the db file {$this->dbFile}");
}
}
fseek($this->dbFileHandler, 8);
$buffer = fread($this->dbFileHandler, TOTAL_HEADER_LENGTH);
//fill the header
$idx = 0;
$this->HeaderSip = array();
$this->HeaderPtr = array();
for ( $i = 0; $i < TOTAL_HEADER_LENGTH; $i += 8 ) {
$startIp = self::getLong($buffer, $i);
$dataPtr = self::getLong($buffer, $i + 4);
if ( $dataPtr == 0 ) break;
$this->HeaderSip[] = $startIp;
$this->HeaderPtr[] = $dataPtr;
$idx++;
}
$this->headerLen = $idx;
}
//1. define the index block with the binary search
$l = 0; $h = $this->headerLen; $sptr = 0; $eptr = 0;
while ( $l <= $h ) {
$m = (($l + $h) >> 1);
//perfetc matched, just return it
if ( $ip == $this->HeaderSip[$m] ) {
if ( $m > 0 ) {
$sptr = $this->HeaderPtr[$m-1];
$eptr = $this->HeaderPtr[$m ];
} else {
$sptr = $this->HeaderPtr[$m ];
$eptr = $this->HeaderPtr[$m+1];
}
break;
}
//less then the middle value
if ( $ip < $this->HeaderSip[$m] ) {
if ( $m == 0 ) {
$sptr = $this->HeaderPtr[$m ];
$eptr = $this->HeaderPtr[$m+1];
break;
} else if ( $ip > $this->HeaderSip[$m-1] ) {
$sptr = $this->HeaderPtr[$m-1];
$eptr = $this->HeaderPtr[$m ];
break;
}
$h = $m - 1;
} else {
if ( $m == $this->headerLen - 1 ) {
$sptr = $this->HeaderPtr[$m-1];
$eptr = $this->HeaderPtr[$m ];
break;
} else if ( $ip <= $this->HeaderSip[$m+1] ) {
$sptr = $this->HeaderPtr[$m ];
$eptr = $this->HeaderPtr[$m+1];
break;
}
$l = $m + 1;
}
}
//match nothing just stop it
if ( $sptr == 0 ) return NULL;
//2. search the index blocks to define the data
$blockLen = $eptr - $sptr;
fseek($this->dbFileHandler, $sptr);
$index = fread($this->dbFileHandler, $blockLen + INDEX_BLOCK_LENGTH);
$dataPtr = 0;
$l = 0; $h = $blockLen / INDEX_BLOCK_LENGTH;
while ( $l <= $h ) {
$m = (($l + $h) >> 1);
$p = (int)($m * INDEX_BLOCK_LENGTH);
$sip = self::getLong($index, $p);
if ( $ip < $sip ) {
$h = $m - 1;
} else {
$eip = self::getLong($index, $p + 4);
if ( $ip > $eip ) {
$l = $m + 1;
} else {
$dataPtr = self::getLong($index, $p + 8);
break;
}
}
}
//not matched
if ( $dataPtr == 0 ) return NULL;
//3. get the data
$dataLen = (($dataPtr >> 24) & 0xFF);
$dataPtr = ($dataPtr & 0x00FFFFFF);
fseek($this->dbFileHandler, $dataPtr);
$data = fread($this->dbFileHandler, $dataLen);
return array(
'city_id' => self::getLong($data, 0),
'region' => substr($data, 4)
);
}
/**
* safe self::safeIp2long function
*
* @param ip
* */
public static function safeIp2long($ip)
{
$ip = ip2long($ip);
// convert signed int to unsigned int if on 32 bit operating system
if ($ip < 0 && PHP_INT_SIZE == 4) {
$ip = sprintf("%u", $ip);
}
return $ip;
}
/**
* read a long from a byte buffer
*
* @param b
* @param offset
*/
public static function getLong( $b, $offset )
{
$val = (
(ord($b[$offset++])) |
(ord($b[$offset++]) << 8) |
(ord($b[$offset++]) << 16) |
(ord($b[$offset ]) << 24)
);
// convert signed int to unsigned int if on 32 bit operating system
if ($val < 0 && PHP_INT_SIZE == 4) {
$val = sprintf("%u", $val);
}
return $val;
}
/**
* destruct method, resource destroy
*/
public function __destruct()
{
if ( $this->dbFileHandler != NULL ) {
fclose($this->dbFileHandler);
}
$this->dbBinStr = NULL;
$this->HeaderSip = NULL;
$this->HeaderPtr = NULL;
}
}

View File

@ -1,66 +0,0 @@
<?php
/**
* Ip2Region php client test script
*
* @author chenxin<chenxin619315@gmail.com>
*/
if ( $argc < 2 ) {
$usage = <<<EOF
Usage: php Test.php [ip2region db file] [alrogrithm]
+-Optional Algorithm: binary, b-tree, memory\n
EOF;
exit($usage);
}
array_shift($argv);
$dbFile = $argv[0];
$method = 'btreeSearch';
$algorithm = 'B-tree';
if ( isset($argv[1]) ) {
switch ( strtolower($argv[1]) ) {
case 'binary':
$algorithm = 'Binary';
$method = 'binarySearch';
break;
case 'memory':
$algorithm = 'Memory';
$method = 'memorySearch';
break;
}
}
require dirname(__FILE__) . '/Ip2Region.class.php';
$ip2regionObj = new Ip2Region($dbFile);
$initStr = <<<INIT
initializing {$algorithm} ...
+----------------------------------+
| ip2region test script |
| Author: chenxin619315@gmail.com |
| Type 'quit' to exit program |
+----------------------------------+
INIT;
echo $initStr, "\n";
while ( true ) {
echo "ip2region>> ";
$line = trim(fgets(STDIN));
if ( strlen($line) < 2 ) continue;
if ( $line == 'quit' ) break;
if ( ip2long($line) == NULL ) {
echo "Error: invalid ip address\n";
continue;
}
$s_time = getTime();
$data = $ip2regionObj->{$method}($line);
$c_time = getTime() - $s_time;
printf("%s|%s in %.5f millseconds\n", $data['city_id'], $data['region'], $c_time);
}
function getTime()
{
return (microtime(true) * 1000);
}
?>

View File

@ -1,37 +0,0 @@
.deps
*.lo
*.la
*.swp
*~
.libs
acinclude.m4
aclocal.m4
autom4te.cache
build
config.guess
config.h
config.h.in
config.log
config.nice
config.status
config.sub
configure
configure.in
include
install-sh
libtool
ltmain.sh
Makefile
Makefile.fragments
Makefile.global
Makefile.objects
missing
mkinstalldirs
modules
run-tests.php
tests/*/*.diff
tests/*/*.out
tests/*/*.php
tests/*/*.exp
tests/*/*.log
tests/*/*.sh

View File

@ -1,2 +0,0 @@
ip2region

View File

@ -1,29 +0,0 @@
# ip2region client - PHP扩展(php5版本)
### 安装步骤
* git clone https://github.com/lionsoul2014/ip2region.git
* cd ip2region
* cp binding/php5_ext 到 php source code 的 ext/ip2region 目录下
* cp binding/c/ 里面所有的文件到 php source code 的 ext/ip2region/lib 目录下
* 在 ext/ip2region 下,运行
phpize
./configure
make && sudo make install
* 配置 ip2region.ini 指定 db_file 路径,(cli/fpm)
extension=ip2region.so
ip2region.db_file=/path/to/ip2region.db
默认 ip2region.db 在项目根目录下的 data 文件夹下,如有改动,请修改 ip2region.ini 的 db_file
* 测试
在 ext/ip2region/ 下运行
php ip2region.php
### 使用
参考当前目录下的 ip2region.php

View File

@ -1,63 +0,0 @@
dnl $Id$
dnl config.m4 for extension ip2region
dnl Comments in this file start with the string 'dnl'.
dnl Remove where necessary. This file will not work
dnl without editing.
dnl If your extension references something external, use with:
dnl PHP_ARG_WITH(ip2region, for ip2region support,
dnl Make sure that the comment is aligned:
dnl [ --with-ip2region Include ip2region support])
dnl Otherwise use enable:
PHP_ARG_ENABLE(ip2region, whether to enable ip2region support,
Make sure that the comment is aligned:
[ --enable-ip2region Enable ip2region support])
if test "$PHP_IP2REGION" != "no"; then
dnl dnl Write more examples of tests here...
dnl
dnl dnl # --with-ip2region -> check with-path
dnl SEARCH_PATH="/home/slayer/code/php-5.6.7/ext/ip2region/lib " # you might want to change this
dnl SEARCH_FOR="ip2region.h" # you most likely want to change this
dnl if test -r $PHP_IP2REGION/$SEARCH_FOR; then # path given as parameter
dnl IP2REGION_DIR=$PHP_IP2REGION
dnl else # search default path list
dnl AC_MSG_CHECKING([for ip2region files in default path])
dnl for i in $SEARCH_PATH ; do
dnl if test -r $i/$SEARCH_FOR; then
dnl IP2REGION_DIR=$i
dnl AC_MSG_RESULT(found in $i)
dnl fi
dnl done
dnl fi
dnl
dnl if test -z "$IP2REGION_DIR"; then
dnl AC_MSG_RESULT([not found])
dnl AC_MSG_ERROR([Please reinstall the ip2region distribution])
dnl fi
dnl
dnl dnl # --with-ip2region -> add include path
dnl PHP_ADD_INCLUDE($IP2REGION_DIR/include)
dnl
dnl dnl # --with-ip2region -> check for lib and symbol presence
dnl LIBNAME=ip2region # you may want to change this
dnl LIBSYMBOL=ip2region # you most likely want to change this
dnl
dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,
dnl [
dnl PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $IP2REGION_DIR/$PHP_LIBDIR, IP2REGION_SHARED_LIBADD)
dnl AC_DEFINE(HAVE_IP2REGIONLIB,1,[ ])
dnl ],[
dnl AC_MSG_ERROR([wrong ip2region lib version or lib not found])
dnl ],[
dnl -L$IP2REGION_DIR/$PHP_LIBDIR -lm
dnl ])
dnl
dnl PHP_SUBST(IP2REGION_SHARED_LIBADD)
dnl
PHP_NEW_EXTENSION(ip2region, ip2region.c lib/ip2region.c , $ext_shared)
fi

View File

@ -1,12 +0,0 @@
// $Id$
//
// If your extension references something external, use ARG_WITH
// ARG_WITH("ip2region", "for ip2region support", "no");
// Otherwise, use ARG_ENABLE
// ARG_ENABLE("ip2region", "enable ip2region support", "no");
if (PHP_IP2REGION != "no") {
EXTENSION("ip2region", "ip2region.c");
}

View File

@ -1,309 +0,0 @@
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2015 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: dongyado<dongyado@gmail.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "lib/ip2region.h"
#include "php_ip2region.h"
#include <sys/time.h>
ZEND_DECLARE_MODULE_GLOBALS(ip2region)
/* True global resources - no need for thread safety here */
static int le_ip2region;
static ip2region_t g_resource_ptr;
static ip2region_entry g_resource;
// class
static zend_class_entry *ip2region_class_entry_ptr;
//static double getTime()
//{
// struct timeval tv;
// struct timezone tz;
// gettimeofday(&tv, &tz);
//
// return (tv.tv_sec * 1000 + ((double)tv.tv_usec)/1000);
//}
static void search(
ip2region_t g_resouce_ptr,
uint_t (*func_ptr) (ip2region_t, uint_t, datablock_t),
long ip,
zval ** return_value,
datablock_t _block)
{
int res = 0;
if (g_resource_ptr != NULL){
res = (*func_ptr)(g_resouce_ptr, (uint_t) ip, _block);
}
array_init( *return_value );
if ( res == 1 )
{
add_assoc_long( *return_value, "city_id", (*_block).city_id);
add_assoc_string( *return_value, "region", (*_block).region, 1);
} else {
add_assoc_long( *return_value, "city_id", 0);
add_assoc_string( *return_value, "region", "[Error] Search Failed! Please check the path of ip2region db file.", 1);
}
}
/* {{{ php_ip2region_init_globals
*/
static void php_ip2region_init_globals(zend_ip2region_globals *ip2region_globals)
{
ip2region_globals->db_file = NULL;
}
/* }}} */
/* {{{ PHP_INI
*/
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("ip2region.db_file", NULL, PHP_INI_ALL, OnUpdateString, db_file, zend_ip2region_globals, ip2region_globals)
PHP_INI_END()
/* }}} */
/* {{{
* btree search string
* */
PHP_METHOD(ip2region_class_entry_ptr, btreeSearchString)
{
char *ip = NULL;
int arg_len;
datablock_entry _block;
uint_t (*func_ptr) (ip2region_t, uint_t, datablock_t);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &ip, &arg_len) == FAILURE) {
return;
}
func_ptr = ip2region_btree_search;
search(g_resource_ptr, func_ptr, ip2long(ip), &return_value, &_block);
}
/* }}} */
/* {{{
* btree search
* */
PHP_METHOD(ip2region_class_entry_ptr, btreeSearch)
{
long ip;
datablock_entry _block;
uint_t (*func_ptr) (ip2region_t, uint_t, datablock_t);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &ip) == FAILURE) {
return;
}
func_ptr = ip2region_btree_search;
search(g_resource_ptr, func_ptr, ip, &return_value, &_block);
}
/* }}} */
/* {{{
* binary search string
* */
PHP_METHOD(ip2region_class_entry_ptr, binarySearchString)
{
char *ip = NULL;
int arg_len;
datablock_entry _block;
uint_t (*func_ptr) (ip2region_t, uint_t, datablock_t);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &ip, &arg_len) == FAILURE) {
return;
}
func_ptr = ip2region_binary_search;
search(g_resource_ptr, func_ptr, ip2long(ip), &return_value, &_block);
}
/* }}} */
/* {{{
* binary search
* */
PHP_METHOD(ip2region_class_entry_ptr, binarySearch)
{
long ip;
datablock_entry _block;
uint_t (*func_ptr) (ip2region_t, uint_t, datablock_t);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &ip) == FAILURE) {
return;
}
func_ptr = ip2region_binary_search;
search(g_resource_ptr, func_ptr, ip, &return_value, &_block);
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(ip2region)
{
UNREGISTER_INI_ENTRIES();
if(g_resource_ptr != NULL) ip2region_destroy(&g_resource);
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(ip2region)
{
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(ip2region)
{
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(ip2region)
{
php_info_print_table_start();
php_info_print_table_header(2, "ip2region support", "enabled");
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
/* {{{ ip2region_class_functions[]
*
* Every user visible function must have an entry in ip2region_functions[].
*/
const zend_function_entry ip2region_class_functions[] = {
PHP_ME( ip2region_class_entry_ptr, btreeSearchString, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME( ip2region_class_entry_ptr, binarySearchString, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC )
PHP_ME( ip2region_class_entry_ptr, btreeSearch, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME( ip2region_class_entry_ptr, binarySearch, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC )
PHP_FE_END /* Must be the last line in ip2region_functions[] */
};
/* }}} */
/* {{{ ip2region_functions[]
*
* Every user visible function must have an entry in ip2region_functions[].
*/
const zend_function_entry ip2region_functions[] = {
PHP_FE_END /* Must be the last line in ip2region_functions[] */
};
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(ip2region)
{
zend_class_entry ip2region_class_entry;
// @NOTE the line should before REGISTRE_INI_ENTRIES,
// and should not comment it when you have glocbals
ZEND_INIT_MODULE_GLOBALS(ip2region, php_ip2region_init_globals, NULL);
REGISTER_INI_ENTRIES();
char* _db_file = IP2REGION_G(db_file);
if ( _db_file == NULL || ip2region_create( &g_resource, _db_file) == 0)
{
g_resource_ptr = NULL;
} else {
g_resource_ptr = &g_resource;
}
//le_ip2region = zend_register_list_destructors_ex(
// ip2region_destruction_handler, NULL, le_ip2region_name, module_number);
// init class
INIT_CLASS_ENTRY( ip2region_class_entry, "ip2region", ip2region_class_functions);
ip2region_class_entry_ptr =
zend_register_internal_class(&ip2region_class_entry TSRMLS_CC);
return SUCCESS;
}
/* }}} */
/* {{{ ip2region_module_entry
*/
zend_module_entry ip2region_module_entry = {
STANDARD_MODULE_HEADER,
"ip2region",
ip2region_functions,
PHP_MINIT(ip2region),
PHP_MSHUTDOWN(ip2region),
PHP_RINIT(ip2region),
PHP_RSHUTDOWN(ip2region),
PHP_MINFO(ip2region),
PHP_IP2REGION_VERSION,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_IP2REGION
ZEND_GET_MODULE(ip2region)
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/

View File

@ -1,67 +0,0 @@
<?php
/**
* test shell for ip2region for php
*
* */
$br = (php_sapi_name() == "cli")? "":"<br>";
if(!extension_loaded('ip2region')) {
dl('ip2region.' . PHP_SHLIB_SUFFIX);
}
function getTime(){
return microtime(true) * 1000;
}
// test class
function classBtreeSearch( $ip)
{
$start = getTime();
//$data = $ip2region->btreeSearch($ip);
$data = Ip2region::btreeSearchString($ip);
$end = getTime();
var_dump($data);
echo " btree search string - taken: ", ($end - $start), "\n";
$start = getTime();
$data = Ip2region:: btreeSearch(ip2long($ip));
$end = getTime();
var_dump($data);
echo " btree search - taken: ", ($end - $start), "\n";
}
function classBinarySearch($ip)
{
$start = getTime();
$data = Ip2region::binarySearchString($ip);
$end = getTime();
var_dump($data);
echo " binary search string -taken: ", ($end - $start), "\n";
$start = getTime();
$data = Ip2region::binarySearch(ip2long($ip));
$end = getTime();
var_dump($data);
echo " binary search - taken: ", ($end - $start), "\n";
}
function test(){
$v1 = rand(0,255);
$v2 = rand(0,255);
$v3 = rand(0,255);
$v4 = rand(0,255);
$ip = "{$v1}.{$v2}.{$v3}.{$v4}";
classBtreeSearch( $ip );
classBinarySearch( $ip );
}
while(true)
{
test();
break;
usleep(5000);
}
?>

View File

@ -1,4 +0,0 @@
这里放置
https://github.com/lionsoul2016/ip2region/tree/master/binding/c
ip2region.c and ip2region.h

View File

@ -1,77 +0,0 @@
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2015 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: dongyado<dongyado@gmail.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_IP2REGION_H
#define PHP_IP2REGION_H
extern zend_module_entry ip2region_module_entry;
#define phpext_ip2region_ptr &ip2region_module_entry
#define PHP_IP2REGION_VERSION "0.1.0" /* Replace with version number for your extension */
#ifdef PHP_WIN32
# define PHP_IP2REGION_API __declspec(dllexport)
#elif defined(__GNUC__) && __GNUC__ >= 4
# define PHP_IP2REGION_API __attribute__ ((visibility("default")))
#else
# define PHP_IP2REGION_API
#endif
#ifdef ZTS
#include "TSRM.h"
#endif
ZEND_BEGIN_MODULE_GLOBALS(ip2region)
char *db_file;
ZEND_END_MODULE_GLOBALS(ip2region)
/* In every utility function you add that needs to use variables
in php_ip2region_globals, call TSRMLS_FETCH(); after declaring other
variables used by that function, or better yet, pass in TSRMLS_CC
after the last function argument and declare your utility function
with TSRMLS_DC after the last declared argument. Always refer to
the globals in your function as IP2REGION_G(variable). You are
encouraged to rename these macros something shorter, see
examples in any other php module directory.
*/
#ifdef ZTS
#define IP2REGION_G(v) TSRMG(ip2region_globals_id, zend_ip2region_globals *, v)
#else
#define IP2REGION_G(v) (ip2region_globals.v)
#endif
static void php_ip2region_init_globals(zend_ip2region_globals *);
#define le_ip2region_name "Ip2region"
#endif /* PHP_IP2REGION_H */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/

View File

@ -1,22 +0,0 @@
--TEST--
Check for ip2region presence
--SKIPIF--
<?php if (!extension_loaded("ip2region")) print "skip"; ?>
--FILE--
<?php
echo "ip2region extension is available";
/*
you can add regression tests for your extension here
the output of your test code has to be equal to the
text in the --EXPECT-- section below for the tests
to pass, differences between the output and the
expected text are interpreted as failure
see php5/README.TESTING for further information on
writing regression tests
*/
?>
--EXPECT--
ip2region extension is available

View File

@ -1,37 +0,0 @@
.deps
*.lo
*.la
*.swp
*~
.libs
acinclude.m4
aclocal.m4
autom4te.cache
build
config.guess
config.h
config.h.in
config.log
config.nice
config.status
config.sub
configure
configure.in
include
install-sh
libtool
ltmain.sh
Makefile
Makefile.fragments
Makefile.global
Makefile.objects
missing
mkinstalldirs
modules
run-tests.php
tests/*/*.diff
tests/*/*.out
tests/*/*.php
tests/*/*.exp
tests/*/*.log
tests/*/*.sh

View File

@ -1,2 +0,0 @@
ip2region

View File

@ -1,29 +0,0 @@
# ip2region client - PHP扩展(php7版本)
### 安装步骤
* git clone https://github.com/lionsoul2014/ip2region.git
* cd ip2region
* cp binding/php7_ext 到 php source code 的 ext/ip2region 目录下
* cp binding/c/ 里面所有的文件到 php source code 的 ext/ip2region/lib 目录下
* 在 ext/ip2region 下,运行
phpize
./configure
make && sudo make install
* 配置 ip2region.ini 指定 db_file 路径,(cli/fpm)
extension=ip2region.so
ip2region.db_file=/path/to/ip2region.db
默认 ip2region.db 在项目根目录下的 data 文件夹下,如有改动,请修改 ip2region.ini 的 db_file
* 测试
在 ext/ip2region/ 下运行
php ip2region.php
### 使用
参考当前目录下的 ip2region.php

View File

@ -1,63 +0,0 @@
dnl $Id$
dnl config.m4 for extension ip2region
dnl Comments in this file start with the string 'dnl'.
dnl Remove where necessary. This file will not work
dnl without editing.
dnl If your extension references something external, use with:
dnl PHP_ARG_WITH(ip2region, for ip2region support,
dnl Make sure that the comment is aligned:
dnl [ --with-ip2region Include ip2region support])
dnl Otherwise use enable:
PHP_ARG_ENABLE(ip2region, whether to enable ip2region support,
Make sure that the comment is aligned:
[ --enable-ip2region Enable ip2region support])
if test "$PHP_IP2REGION" != "no"; then
dnl dnl Write more examples of tests here...
dnl
dnl dnl # --with-ip2region -> check with-path
dnl SEARCH_PATH="/home/slayer/code/php-5.6.7/ext/ip2region/lib " # you might want to change this
dnl SEARCH_FOR="ip2region.h" # you most likely want to change this
dnl if test -r $PHP_IP2REGION/$SEARCH_FOR; then # path given as parameter
dnl IP2REGION_DIR=$PHP_IP2REGION
dnl else # search default path list
dnl AC_MSG_CHECKING([for ip2region files in default path])
dnl for i in $SEARCH_PATH ; do
dnl if test -r $i/$SEARCH_FOR; then
dnl IP2REGION_DIR=$i
dnl AC_MSG_RESULT(found in $i)
dnl fi
dnl done
dnl fi
dnl
dnl if test -z "$IP2REGION_DIR"; then
dnl AC_MSG_RESULT([not found])
dnl AC_MSG_ERROR([Please reinstall the ip2region distribution])
dnl fi
dnl
dnl dnl # --with-ip2region -> add include path
dnl PHP_ADD_INCLUDE($IP2REGION_DIR/include)
dnl
dnl dnl # --with-ip2region -> check for lib and symbol presence
dnl LIBNAME=ip2region # you may want to change this
dnl LIBSYMBOL=ip2region # you most likely want to change this
dnl
dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,
dnl [
dnl PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $IP2REGION_DIR/$PHP_LIBDIR, IP2REGION_SHARED_LIBADD)
dnl AC_DEFINE(HAVE_IP2REGIONLIB,1,[ ])
dnl ],[
dnl AC_MSG_ERROR([wrong ip2region lib version or lib not found])
dnl ],[
dnl -L$IP2REGION_DIR/$PHP_LIBDIR -lm
dnl ])
dnl
dnl PHP_SUBST(IP2REGION_SHARED_LIBADD)
dnl
PHP_NEW_EXTENSION(ip2region, ip2region.c lib/ip2region.c , $ext_shared)
fi

View File

@ -1,12 +0,0 @@
// $Id$
//
// If your extension references something external, use ARG_WITH
// ARG_WITH("ip2region", "for ip2region support", "no");
// Otherwise, use ARG_ENABLE
// ARG_ENABLE("ip2region", "enable ip2region support", "no");
if (PHP_IP2REGION != "no") {
EXTENSION("ip2region", "ip2region.c");
}

Some files were not shown because too many files have changed in this diff Show More