first commit
commit
6d9f1a22a3
@ -0,0 +1,47 @@
|
||||
*.class
|
||||
*.out
|
||||
*.o
|
||||
*.pyc
|
||||
*~
|
||||
*.log
|
||||
*.la
|
||||
*.so
|
||||
META-INF/
|
||||
*.zip
|
||||
|
||||
# Package Files #
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
||||
|
||||
# vim swp file #
|
||||
*.swp
|
||||
.idea
|
||||
|
||||
# binding
|
||||
/binding/java/classes/
|
||||
/binding/java/doc/
|
||||
/binding/java/target/
|
||||
/binding/java/*.jar
|
||||
|
||||
/binding/c/testSearcher
|
||||
|
||||
# rust
|
||||
Cargo.lock
|
||||
target
|
||||
|
||||
|
||||
# VS ignore cases
|
||||
/**/*.sln
|
||||
/binding/c#/**/.vs/
|
||||
/binding/c#/**/packages
|
||||
/binding/c#/**/bin
|
||||
/binding/c#/**/obj
|
||||
|
||||
# Nodejs
|
||||
/binding/nodejs/tests/unitTests/__snapshots__
|
||||
/binding/nodejs/coverage
|
||||
|
||||
# data
|
||||
/data/ip.merge.txt
|
||||
/data/ip.txt
|
@ -0,0 +1,2 @@
|
||||
[workspace]
|
||||
members = ["binding/rust", "binding/rust/example"]
|
@ -0,0 +1,225 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
==========================================================================
|
||||
The following license applies to the ip2region library
|
||||
--------------------------------------------------------------------------
|
||||
Copyright (c) 2015 Lionsoul<chenxin619315@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
@ -0,0 +1,16 @@
|
||||
<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>
|
Binary file not shown.
@ -0,0 +1,26 @@
|
||||
<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>
|
@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
|
||||
namespace IP2Region.Test.xUnit
|
||||
{
|
||||
public class SearchTest : IDisposable
|
||||
{
|
||||
private readonly DbSearcher _search;
|
||||
|
||||
public SearchTest()
|
||||
{
|
||||
_search = new DbSearcher(Environment.CurrentDirectory + @"\DB\ip2region.db");
|
||||
}
|
||||
[Fact]
|
||||
public void Search_Test()
|
||||
{
|
||||
string memResult = _search.MemorySearch("183.192.62.65").Region;
|
||||
string binarySearchResult = _search.BinarySearch("183.192.62.65").Region;
|
||||
string binaryTreeSearchResult = _search.BtreeSearch("183.192.62.65").Region;
|
||||
|
||||
Assert.NotNull(memResult);
|
||||
Assert.NotNull(binarySearchResult);
|
||||
Assert.NotNull(binaryTreeSearchResult);
|
||||
|
||||
Assert.Equal(memResult, binarySearchResult);
|
||||
Assert.Equal(binaryTreeSearchResult, memResult);
|
||||
}
|
||||
|
||||
[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.
@ -0,0 +1,412 @@
|
||||
//*******************************
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
//*******************************
|
||||
// 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)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
//*******************************
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
//*******************************
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,122 @@
|
||||
//*******************************
|
||||
// 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}";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
|
||||
</startup>
|
||||
</configuration>
|
Binary file not shown.
@ -0,0 +1,42 @@
|
||||
# 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.
|
||||
|
@ -0,0 +1,26 @@
|
||||
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
|
@ -0,0 +1,441 @@
|
||||
/**
|
||||
* 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 ( *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;
|
||||
}
|
@ -0,0 +1,152 @@
|
||||
/**
|
||||
* 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*/
|
@ -0,0 +1,102 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
@ -0,0 +1,328 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
@ -0,0 +1,138 @@
|
||||
/**
|
||||
* 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*/
|
@ -0,0 +1,99 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
@ -0,0 +1,89 @@
|
||||
### 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
|
||||
|
||||
```
|
@ -0,0 +1,349 @@
|
||||
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
|
||||
}
|
||||
|
@ -0,0 +1,49 @@
|
||||
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)
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
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()))
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
<?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>
|
@ -0,0 +1,190 @@
|
||||
<?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>3.8.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>
|
@ -0,0 +1,86 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
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;
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
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);
|
||||
}
|
||||
}
|
@ -0,0 +1,405 @@
|
||||
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 bianry string support
|
||||
* Thanks to the issue from Wendal at https://gitee.com/lionsoul/ip2region/issues/IILFL
|
||||
*
|
||||
* @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;
|
||||
raf.close();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
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;
|
||||
}
|
||||
}
|
@ -0,0 +1,113 @@
|
||||
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;
|
||||
}
|
||||
}
|
@ -0,0 +1,143 @@
|
||||
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;
|
||||
}
|
||||
}
|
@ -0,0 +1,120 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
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"));
|
||||
}
|
||||
}
|
@ -0,0 +1,443 @@
|
||||
--[[
|
||||
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;
|
@ -0,0 +1,85 @@
|
||||
--[[
|
||||
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();
|
@ -0,0 +1,28 @@
|
||||
# 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
|
@ -0,0 +1,232 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
@ -0,0 +1,86 @@
|
||||
--[[
|
||||
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();
|
@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
data/
|
@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"tabWidth": 4
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
#!/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
|
@ -0,0 +1,634 @@
|
||||
/**
|
||||
* 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
@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "lionsoul-ip2region",
|
||||
"version": "0.0.1",
|
||||
"description": "ip database ",
|
||||
"main": "ip2region.js",
|
||||
"scripts": {
|
||||
"test": "jest",
|
||||
"coverage": "npm run test && jest --coverage"
|
||||
},
|
||||
"files": ["data/"],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/lionsoul2016/ip2region"
|
||||
},
|
||||
"keywords": [
|
||||
"ip2region",
|
||||
"ip",
|
||||
"region"
|
||||
],
|
||||
"author": "dongyado",
|
||||
"license": "ISC",
|
||||
"bugs": {
|
||||
"url": "https://github.com/lionsoul2016/ip2region/issues"
|
||||
},
|
||||
"homepage": "https://github.com/lionsoul2016/ip2region",
|
||||
"devDependencies": {
|
||||
"jest": "^19.0.2",
|
||||
"benchmark": "^2.1.4"
|
||||
}
|
||||
}
|
@ -0,0 +1,94 @@
|
||||
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 });
|
@ -0,0 +1,145 @@
|
||||
// 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
|
||||
});
|
@ -0,0 +1,146 @@
|
||||
// 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
|
||||
});
|
@ -0,0 +1,28 @@
|
||||
// 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();
|
||||
});
|
||||
|
||||
});
|
@ -0,0 +1,23 @@
|
||||
/**
|
||||
* 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;
|
@ -0,0 +1,9 @@
|
||||
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;
|
@ -0,0 +1,16 @@
|
||||
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
@ -0,0 +1,360 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
<?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);
|
||||
}
|
||||
?>
|
@ -0,0 +1,37 @@
|
||||
.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
|
@ -0,0 +1,2 @@
|
||||
ip2region
|
||||
|
@ -0,0 +1,29 @@
|
||||
# ip2region client - PHP扩展(php5版本)
|
||||
|
||||
### 安装步骤
|
||||
* git clone https://github.com/lionsoul2014/ip2region.git
|
||||
* cd ip2region
|
||||
* cp binding/php_extension/php5/ip2region 到 php source code 的 ext 目录下
|
||||
* 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
|
@ -0,0 +1,63 @@
|
||||
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
|
@ -0,0 +1,12 @@
|
||||
// $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");
|
||||
}
|
||||
|
@ -0,0 +1,309 @@
|
||||
/*
|
||||
+----------------------------------------------------------------------+
|
||||
| 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);
|
||||
//}
|
||||
|
||||
|
||||
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();
|
||||
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();
|
||||
|
||||
|
||||
if (ip2region_create( &g_resource, IP2REGION_G(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
|
||||
*/
|
@ -0,0 +1,67 @@
|
||||
<?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);
|
||||
}
|
||||
?>
|
@ -0,0 +1,4 @@
|
||||
这里放置
|
||||
https://github.com/lionsoul2016/ip2region/tree/master/binding/c
|
||||
|
||||
ip2region.c and ip2region.h
|
@ -0,0 +1,78 @@
|
||||
/*
|
||||
+----------------------------------------------------------------------+
|
||||
| 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"
|
||||
|
||||
|
||||
void search( ip2region_t, uint_t (*func_ptr) (ip2region_t, uint_t, datablock_t), long , zval **, datablock_t);
|
||||
|
||||
#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
|
||||
*/
|
@ -0,0 +1,22 @@
|
||||
--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
|
@ -0,0 +1,37 @@
|
||||
.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
|
@ -0,0 +1,2 @@
|
||||
ip2region
|
||||
|
@ -0,0 +1,29 @@
|
||||
# ip2region client - PHP扩展(php7版本)
|
||||
|
||||
### 安装步骤
|
||||
* git clone https://github.com/lionsoul2014/ip2region.git
|
||||
* cd ip2region
|
||||
* cp binding/php_extension/php7/ip2region 到 php source code 的 ext 目录下
|
||||
* 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
|
@ -0,0 +1,63 @@
|
||||
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
|
@ -0,0 +1,12 @@
|
||||
// $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");
|
||||
}
|
||||
|
@ -0,0 +1,315 @@
|
||||
/*
|
||||
+----------------------------------------------------------------------+
|
||||
| PHP Version 7 |
|
||||
+----------------------------------------------------------------------+
|
||||
| Copyright (c) 1997-2016 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);
|
||||
//}
|
||||
|
||||
|
||||
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);
|
||||
// for phpng
|
||||
add_assoc_string( *return_value, "region", (*_block).region);
|
||||
} 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);
|
||||
// for phpng
|
||||
add_assoc_string( *return_value, "region", "[Error] Search Failed! Please check the path of ip2region db file.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* {{{ 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;
|
||||
size_t 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;
|
||||
// for phpng
|
||||
size_t 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();
|
||||
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();
|
||||
|
||||
|
||||
if (ip2region_create( &g_resource, IP2REGION_G(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
|
||||
*/
|
@ -0,0 +1,67 @@
|
||||
<?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);
|
||||
}
|
||||
?>
|
@ -0,0 +1,4 @@
|
||||
这里放置
|
||||
https://github.com/lionsoul2016/ip2region/tree/master/binding/c
|
||||
|
||||
ip2region.c and ip2region.h
|
@ -0,0 +1,78 @@
|
||||
/*
|
||||
+----------------------------------------------------------------------+
|
||||
| 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"
|
||||
|
||||
|
||||
void search( ip2region_t, uint_t (*func_ptr) (ip2region_t, uint_t, datablock_t), long , zval **, datablock_t);
|
||||
|
||||
#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
|
||||
*/
|
@ -0,0 +1,22 @@
|
||||
--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
|
@ -0,0 +1,54 @@
|
||||
#-*- coding:utf-8 -*-
|
||||
"""
|
||||
" ip2region python seacher client module benchmark test file
|
||||
"
|
||||
" Autho: koma<komazhang@foxmail.com>
|
||||
" Date : 2018-10-04
|
||||
"""
|
||||
import threading
|
||||
import time, sys
|
||||
|
||||
from ip2Region import Ip2Region
|
||||
|
||||
class BenchmarkThread(threading.Thread):
|
||||
__searcher = None
|
||||
__lock = None
|
||||
|
||||
def __init__(self, searcher, lock):
|
||||
self.__searcher = searcher
|
||||
self.__lock = lock
|
||||
threading.Thread.__init__(self)
|
||||
|
||||
def run(self):
|
||||
self.__lock.acquire()
|
||||
try:
|
||||
sTime = time.time() * 1000
|
||||
data = self.__searcher.memorySearch("49.220.138.233")
|
||||
eTime = time.time() * 1000
|
||||
# @Note uncomment the print to make it more like the product environment
|
||||
print("%s|%s in %5f millseconds" % (data["city_id"], data["region"].decode('utf-8'), eTime - sTime))
|
||||
finally:
|
||||
self.__lock.release()
|
||||
|
||||
if __name__ == "__main__":
|
||||
dbFile = "./data/ip2region.db"
|
||||
if ( len(sys.argv) > 2 ):
|
||||
dbFile = sys.argv[1];
|
||||
|
||||
threads = []
|
||||
searcher = Ip2Region(dbFile)
|
||||
lock = threading.Lock()
|
||||
|
||||
for i in range(10000):
|
||||
t = BenchmarkThread(searcher, lock)
|
||||
threads.append(t)
|
||||
|
||||
sTime = time.time() * 1000
|
||||
for t in threads:
|
||||
t.start()
|
||||
|
||||
for t in threads:
|
||||
t.join()
|
||||
eTime = time.time() * 1000
|
||||
|
||||
print("Benchmark done: %5f" % (eTime - sTime))
|
@ -0,0 +1,232 @@
|
||||
#-*- coding:utf-8 -*-
|
||||
"""
|
||||
" ip2region python seacher client module
|
||||
"
|
||||
" Author: koma<komazhang@foxmail.com>
|
||||
" Date : 2015-11-06
|
||||
"""
|
||||
import struct, io, socket, sys
|
||||
|
||||
class Ip2Region(object):
|
||||
__INDEX_BLOCK_LENGTH = 12
|
||||
__TOTAL_HEADER_LENGTH = 8192
|
||||
|
||||
__f = None
|
||||
__headerSip = []
|
||||
__headerPtr = []
|
||||
__headerLen = 0
|
||||
__indexSPtr = 0
|
||||
__indexLPtr = 0
|
||||
__indexCount = 0
|
||||
__dbBinStr = ''
|
||||
|
||||
def __init__(self, dbfile):
|
||||
self.initDatabase(dbfile)
|
||||
|
||||
def memorySearch(self, ip):
|
||||
"""
|
||||
" memory search method
|
||||
" param: ip
|
||||
"""
|
||||
if not ip.isdigit(): ip = self.ip2long(ip)
|
||||
|
||||
if self.__dbBinStr == '':
|
||||
self.__dbBinStr = self.__f.read() #read all the contents in file
|
||||
self.__indexSPtr = self.getLong(self.__dbBinStr, 0)
|
||||
self.__indexLPtr = self.getLong(self.__dbBinStr, 4)
|
||||
self.__indexCount = int((self.__indexLPtr - self.__indexSPtr)/self.__INDEX_BLOCK_LENGTH)+1
|
||||
|
||||
l, h, dataPtr = (0, self.__indexCount, 0)
|
||||
while l <= h:
|
||||
m = int((l+h) >> 1)
|
||||
p = self.__indexSPtr + m*self.__INDEX_BLOCK_LENGTH
|
||||
sip = self.getLong(self.__dbBinStr, p)
|
||||
|
||||
if ip < sip:
|
||||
h = m -1
|
||||
else:
|
||||
eip = self.getLong(self.__dbBinStr, p+4)
|
||||
if ip > eip:
|
||||
l = m + 1;
|
||||
else:
|
||||
dataPtr = self.getLong(self.__dbBinStr, p+8)
|
||||
break
|
||||
|
||||
if dataPtr == 0: raise Exception("Data pointer not found")
|
||||
|
||||
return self.returnData(dataPtr)
|
||||
|
||||
def binarySearch(self, ip):
|
||||
"""
|
||||
" binary search method
|
||||
" param: ip
|
||||
"""
|
||||
if not ip.isdigit(): ip = self.ip2long(ip)
|
||||
|
||||
if self.__indexCount == 0:
|
||||
self.__f.seek(0)
|
||||
superBlock = self.__f.read(8)
|
||||
self.__indexSPtr = self.getLong(superBlock, 0)
|
||||
self.__indexLPtr = self.getLong(superBlock, 4)
|
||||
self.__indexCount = int((self.__indexLPtr - self.__indexSPtr) / self.__INDEX_BLOCK_LENGTH) + 1
|
||||
|
||||
l, h, dataPtr = (0, self.__indexCount, 0)
|
||||
while l <= h:
|
||||
m = int((l+h) >> 1)
|
||||
p = m*self.__INDEX_BLOCK_LENGTH
|
||||
|
||||
self.__f.seek(self.__indexSPtr+p)
|
||||
buffer = self.__f.read(self.__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
|
||||
|
||||
if dataPtr == 0: raise Exception("Data pointer not found")
|
||||
|
||||
return self.returnData(dataPtr)
|
||||
|
||||
def btreeSearch(self, ip):
|
||||
"""
|
||||
" b-tree search method
|
||||
" param: ip
|
||||
"""
|
||||
if not ip.isdigit(): ip = self.ip2long(ip)
|
||||
|
||||
if len(self.__headerSip) < 1:
|
||||
headerLen = 0
|
||||
#pass the super block
|
||||
self.__f.seek(8)
|
||||
#read the header block
|
||||
b = self.__f.read(self.__TOTAL_HEADER_LENGTH)
|
||||
#parse the header block
|
||||
for i in range(0, len(b), 8):
|
||||
sip = self.getLong(b, i)
|
||||
ptr = self.getLong(b, i+4)
|
||||
if ptr == 0:
|
||||
break
|
||||
self.__headerSip.append(sip)
|
||||
self.__headerPtr.append(ptr)
|
||||
headerLen += 1
|
||||
self.__headerLen = headerLen
|
||||
|
||||
l, h, sptr, eptr = (0, self.__headerLen, 0, 0)
|
||||
while l <= h:
|
||||
m = int((l+h) >> 1)
|
||||
|
||||
if ip == self.__headerSip[m]:
|
||||
if m > 0:
|
||||
sptr = self.__headerPtr[m-1]
|
||||
eptr = self.__headerPtr[m]
|
||||
else:
|
||||
sptr = self.__headerPtr[m]
|
||||
eptr = self.__headerPtr[m+1]
|
||||
break
|
||||
|
||||
if ip < self.__headerSip[m]:
|
||||
if m == 0:
|
||||
sptr = self.__headerPtr[m]
|
||||
eptr = self.__headerPtr[m+1]
|
||||
break
|
||||
elif ip > self.__headerSip[m-1]:
|
||||
sptr = self.__headerPtr[m-1]
|
||||
eptr = self.__headerPtr[m]
|
||||
break
|
||||
h = m - 1
|
||||
else:
|
||||
if m == self.__headerLen - 1:
|
||||
sptr = self.__headerPtr[m-1]
|
||||
eptr = self.__headerPtr[m]
|
||||
break
|
||||
elif ip <= self.__headerSip[m+1]:
|
||||
sptr = self.__headerPtr[m]
|
||||
eptr = self.__headerPtr[m+1]
|
||||
break
|
||||
l = m + 1
|
||||
|
||||
if sptr == 0: raise Exception("Index pointer not found")
|
||||
|
||||
indexLen = eptr - sptr
|
||||
self.__f.seek(sptr)
|
||||
index = self.__f.read(indexLen + self.__INDEX_BLOCK_LENGTH)
|
||||
|
||||
l, h, dataPrt = (0, int(indexLen/self.__INDEX_BLOCK_LENGTH), 0)
|
||||
while l <= h:
|
||||
m = int((l+h) >> 1)
|
||||
offset = int(m * self.__INDEX_BLOCK_LENGTH)
|
||||
sip = self.getLong(index, offset)
|
||||
|
||||
if ip < sip:
|
||||
h = m - 1
|
||||
else:
|
||||
eip = self.getLong(index, offset+4)
|
||||
if ip > eip:
|
||||
l = m + 1;
|
||||
else:
|
||||
dataPrt = self.getLong(index, offset+8)
|
||||
break
|
||||
|
||||
if dataPrt == 0: raise Exception("Data pointer not found")
|
||||
|
||||
return self.returnData(dataPrt)
|
||||
|
||||
def initDatabase(self, dbfile):
|
||||
"""
|
||||
" initialize the database for search
|
||||
" param: dbFile
|
||||
"""
|
||||
try:
|
||||
self.__f = io.open(dbfile, "rb")
|
||||
except IOError as e:
|
||||
print("[Error]: %s" % e)
|
||||
sys.exit()
|
||||
|
||||
def returnData(self, dataPtr):
|
||||
"""
|
||||
" get ip data from db file by data start ptr
|
||||
" param: dsptr
|
||||
"""
|
||||
dataLen = (dataPtr >> 24) & 0xFF
|
||||
dataPtr = dataPtr & 0x00FFFFFF
|
||||
|
||||
self.__f.seek(dataPtr)
|
||||
data = self.__f.read(dataLen)
|
||||
|
||||
return {
|
||||
"city_id": self.getLong(data, 0),
|
||||
"region" : data[4:]
|
||||
}
|
||||
|
||||
def ip2long(self, ip):
|
||||
_ip = socket.inet_aton(ip)
|
||||
return struct.unpack("!L", _ip)[0]
|
||||
|
||||
def isip(self, ip):
|
||||
p = ip.split(".")
|
||||
|
||||
if len(p) != 4 : return False
|
||||
for pp in p:
|
||||
if not pp.isdigit() : return False
|
||||
if len(pp) > 3 : return False
|
||||
if int(pp) > 255 : return False
|
||||
|
||||
return True
|
||||
|
||||
def getLong(self, b, offset):
|
||||
if len(b[offset:offset+4]) == 4:
|
||||
return struct.unpack('I', b[offset:offset+4])[0]
|
||||
return 0
|
||||
|
||||
def close(self):
|
||||
if self.__f != None:
|
||||
self.__f.close()
|
||||
|
||||
self.__dbBinStr = None
|
||||
self.__headerPtr = None
|
||||
self.__headerSip = None
|
@ -0,0 +1,83 @@
|
||||
#-*- coding:utf-8 -*-
|
||||
"""
|
||||
" ip2region python seacher client module
|
||||
"
|
||||
" Autho: koma<komazhang@foxmail.com>
|
||||
" Date : 2015-11-06
|
||||
"""
|
||||
import struct, sys, os, time
|
||||
from platform import python_version
|
||||
|
||||
from ip2Region import Ip2Region
|
||||
|
||||
def testSearch():
|
||||
"""
|
||||
" ip2region test function
|
||||
"""
|
||||
argLen = len(sys.argv)
|
||||
version = python_version()
|
||||
algorithms = ["binary", "b-tree", "memory"]
|
||||
|
||||
if argLen < 2:
|
||||
print("Usage: python testSearcher.py [ip2region db file] [alrogrithm]")
|
||||
print("Algorithm: %s" % ", ".join(algorithms))
|
||||
return 0
|
||||
|
||||
dbFile = sys.argv[1]
|
||||
|
||||
if (not os.path.isfile(dbFile)) or (not os.path.exists(dbFile)):
|
||||
print("[Error]: Specified db file is not exists.")
|
||||
return 0
|
||||
|
||||
if argLen > 2:
|
||||
algorithm = sys.argv[2]
|
||||
try:
|
||||
algorithms.index(algorithm)
|
||||
except Exception as e:
|
||||
algorithm = "b-tree"
|
||||
|
||||
print("initializing %s..." % (algorithm))
|
||||
print("+----------------------------------+")
|
||||
print("| ip2region test program |")
|
||||
print("| Author: chenxin619315@gmail.com. |")
|
||||
print("| Type 'quit' to exit program |")
|
||||
print("+----------------------------------+")
|
||||
|
||||
searcher = Ip2Region(dbFile)
|
||||
|
||||
while True:
|
||||
if version[:1] == "2":
|
||||
line = raw_input("ip2region>> ")
|
||||
else:
|
||||
line = input("ip2region>> ")
|
||||
line = line.strip()
|
||||
|
||||
if line == "":
|
||||
print("[Error]: Invalid ip address.")
|
||||
continue
|
||||
|
||||
if line == "quit":
|
||||
print("[Info]: Thanks for your use, Bye.")
|
||||
break
|
||||
|
||||
if not searcher.isip(line):
|
||||
print("[Error]: Invalid ip address.")
|
||||
continue
|
||||
|
||||
try:
|
||||
sTime = time.time()*1000
|
||||
if algorithm == "binary":
|
||||
data = searcher.binarySearch(line)
|
||||
elif algorithm == "memory":
|
||||
data = searcher.memorySearch(line)
|
||||
else:
|
||||
data = searcher.btreeSearch(line)
|
||||
eTime = time.time()*1000
|
||||
print("%s|%s in %5f millseconds" % (data["city_id"], data["region"].decode('utf-8'), eTime - sTime))
|
||||
except Exception as e:
|
||||
print("[Error]: %s" % e)
|
||||
|
||||
searcher.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
testSearch()
|
@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "ip2region"
|
||||
version = "0.2.0"
|
||||
authors = ["biluohc <biluohc@qq.com>"]
|
||||
|
||||
include = ["./*", "../../data/ip2region.db", "../../Cargo.toml"]
|
||||
|
||||
[[bin]]
|
||||
name="ip2region"
|
||||
path="src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
lazy_static ={ version = "^1", optional = true }
|
||||
|
||||
[features]
|
||||
lazy = ["lazy_static"]
|
||||
|
@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "example"
|
||||
version = "0.1.0"
|
||||
authors = ["biluohc <biluohc@qq.com>"]
|
||||
|
||||
[dependencies]
|
||||
|
||||
[dependencies.ip2region]
|
||||
path = "../"
|
||||
# git = "https://github.com/lionsoul2014/ip2region"
|
||||
# git = "https://github.com/biluohc/ip2region"
|
||||
version = "*"
|
||||
features = ["lazy"]
|
@ -0,0 +1,114 @@
|
||||
extern crate ip2region;
|
||||
|
||||
use ip2region::*;
|
||||
|
||||
use std::env;
|
||||
use std::time::Instant;
|
||||
|
||||
// cargo run --release ../../../data/ip2region.db
|
||||
|
||||
static IPS: &'static [&'_ str] = &[
|
||||
"117.136.105.202",
|
||||
"47.95.47.253",
|
||||
"127.0.0.1",
|
||||
"10.0.0.1",
|
||||
"1.1.1.1",
|
||||
];
|
||||
|
||||
fn main() {
|
||||
lazy();
|
||||
|
||||
overview();
|
||||
}
|
||||
|
||||
fn lazy() {
|
||||
for ip in IPS {
|
||||
let start = Instant::now();
|
||||
let res = memory_search(ip);
|
||||
let end = start.elapsed().subsec_micros();
|
||||
println!("lazy__ {:06} microseconds: {:?}", end, res);
|
||||
|
||||
let start = Instant::now();
|
||||
let ip_addr = ip.parse().unwrap();
|
||||
let res2 = memory_search_ip(&ip_addr);
|
||||
let end = start.elapsed().subsec_micros();
|
||||
println!("lazy__ {:06} microseconds: {:?}", end, res2);
|
||||
|
||||
if res.is_ok() && res2.is_ok() {
|
||||
assert_eq!(res.unwrap(), res2.unwrap());
|
||||
} else if res.is_err() && res2.is_err() {
|
||||
} else {
|
||||
panic!("not EQ")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn overview() {
|
||||
let args = env::args().skip(1).collect::<Vec<String>>();
|
||||
let db_path = &args[0];
|
||||
|
||||
let mut ip2 = Ip2Region::new(db_path).unwrap();
|
||||
let ip2o = ip2.to_owned().unwrap();
|
||||
|
||||
for ip in IPS {
|
||||
// mem
|
||||
let start = Instant::now();
|
||||
let res = ip2o.memory_search(ip);
|
||||
let end = start.elapsed().subsec_micros();
|
||||
println!("memory {:06} microseconds: {:?}", end, res);
|
||||
|
||||
let start = Instant::now();
|
||||
let ip_addr = ip.parse().unwrap();
|
||||
let res2 = ip2o.memory_search_ip(&ip_addr);
|
||||
let end = start.elapsed().subsec_micros();
|
||||
println!("memory {:06} microseconds: {:?}", end, res2);
|
||||
|
||||
if res.is_ok() && res2.is_ok() {
|
||||
assert_eq!(res.unwrap(), res2.unwrap());
|
||||
} else if res.is_err() && res2.is_err() {
|
||||
} else {
|
||||
panic!("not EQ")
|
||||
}
|
||||
|
||||
// binary
|
||||
let start = Instant::now();
|
||||
let res = ip2.binary_search(ip);
|
||||
let end = start.elapsed().subsec_micros();
|
||||
println!("binary {:06} microseconds: {:?}", end, res);
|
||||
|
||||
let start = Instant::now();
|
||||
let ip_addr = ip.parse().unwrap();
|
||||
let res2 = ip2.binary_search_ip(&ip_addr);
|
||||
let end = start.elapsed().subsec_micros();
|
||||
println!("binary {:06} microseconds: {:?}", end, res2);
|
||||
|
||||
if res.is_ok() && res2.is_ok() {
|
||||
assert_eq!(res.unwrap(), res2.unwrap());
|
||||
} else if res.is_err() && res2.is_err() {
|
||||
} else {
|
||||
panic!("not EQ")
|
||||
}
|
||||
|
||||
// btree
|
||||
let start = Instant::now();
|
||||
let res = ip2.btree_search(ip);
|
||||
let end = start.elapsed().subsec_micros();
|
||||
println!("btree {:06} microseconds: {:?}", end, res);
|
||||
|
||||
let start = Instant::now();
|
||||
let ip_addr = ip.parse().unwrap();
|
||||
let res2 = ip2.btree_search_ip(&ip_addr);
|
||||
let end = start.elapsed().subsec_micros();
|
||||
println!("btree_ {:06} microseconds: {:?}", end, res2);
|
||||
|
||||
if res.is_ok() && res2.is_ok() {
|
||||
assert_eq!(res.unwrap(), res2.unwrap());
|
||||
} else if res.is_err() && res2.is_err() {
|
||||
} else {
|
||||
panic!("not EQ")
|
||||
}
|
||||
|
||||
// \n
|
||||
println!();
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue