Full Code of ipipdotnet/ipdb-python for AI

master bca2ecdd8f39 cached
16 files
35.0 KB
9.2k tokens
95 symbols
1 requests
Download .txt
Repository: ipipdotnet/ipdb-python
Branch: master
Commit: bca2ecdd8f39
Files: 16
Total size: 35.0 KB

Directory structure:
gitextract_54w2ubn7/

├── .gitignore
├── LICENSE
├── README.md
├── README_en.md
├── example.py
├── ipdb/
│   ├── __init__.py
│   ├── asn.py
│   ├── base_station.py
│   ├── city.py
│   ├── database.py
│   ├── district.py
│   ├── exceptions.py
│   ├── idc.py
│   └── util.py
├── ipdb_test.py
└── setup.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so
.idea
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/


================================================
FILE: LICENSE
================================================
                                 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.


================================================
FILE: README.md
================================================
# ipdb-python
IPIP.net officially supported IP database ipdb format parsing library

# Python Parse ipdb file

## Installing
<pre>
<code>pip install ipip-ipdb</code>
</pre>

## Dependents ( python 2.x or before python 3.3 )
<pre><code>pip install ipaddress</code></pre>

## Code Example
### 适用于IPDB格式
  <pre><code>
import ipdb

db = ipdb.City("/path/to/city.ipv4.ipdb")
# db.reload("/path/to/city.ipv4.ipdb") # update ipdb database file reload data
print(db.is_ipv4(), db.is_ipv6())
print(db.languages()) # support language
print(db.fields()) #  support fields
print(db.build_time()) #  build database time
print(db.find("1.1.1.1", "CN")) #  query ip return array
# print(db.find(u"1.1.1.1", "CN")) #  Python 2.7
print(db.find_map("8.8.8.8", "CN")) #  query ip return dict
print(db.find_info("118.28.1.1", "CN").country_name) 
db.find_info("118.28.1.1", "CN").get_asninfo()
  </pre></code>

### 地级市精度库数据字段说明
<pre>
country_name : 国家名字 
region_name  : 省名字   
city_name    : 城市名字 
owner_domain : 所有者   
isp_domain  : 运营商 
latitude  :  纬度 
longitude : 经度   
timezone : 时区   
utc_offset : UTC时区    
china_admin_code : 中国行政区划代码
idd_code : 国家电话号码前缀 
country_code : 国家2位代码
continent_code : 大洲代码 
idc : IDC |  VPN   
base_station : 基站 | WIFI
country_code3 : 国家3位代码 
european_union : 是否为欧盟成员国: 1 | 0 
currency_code : 当前国家货币代码  
currency_name : 当前国家货币名称   
anycast : ANYCAST     
</pre>

### 适用于IPDB格式的中国地区 IPv4 区县库
  <pre>
import ipdb

db = ipdb.District("/path/to/china_district.ipdb")
print(db.is_ipv4(), db.is_ipv6())
print(db.languages())
print(db.fields())
print(db.build_time())
print(db.find("1.12.13.255", "CN"))
print(db.find_map("1.12.13.255", "CN"))
print(db.find_info("1.12.13.255", "CN").country_name)
  </pre>

### 适用于IPDB格式的 IDC 库
<pre>
import ipdb
>>> db = ipdb.IDC("/path/to/idc_list.ipdb") 
>>> print db.find_info(u"8.142.10.33", "CN").isp_domain
aliyun.com
>>> print db.find_info(u"8.142.10.33", "CN").idc
IDC
</pre>

### 适用于IPDB格式的基站 IPv4 库
<pre>
import ipdb
db = ipdb.BaseStation("/path/to/base_station.ipdb")
print(db.is_ipv4(), db.is_ipv6())
print(db.languages())
print(db.fields())
print(db.build_time())
print(db.find_map("117.136.83.55", "CN"))
</pre>


================================================
FILE: README_en.md
================================================
# ipdb-python
IPIP.net officially supported IP database ipdb format parsing library

# Python Parse ipdb file

## Installing
<pre>
<code>pip install ipip-ipdb</code>
</pre>

## Dependents ( python 2.x or before python 3.3 )
<pre><code>pip install ipaddress</code></pre>

## Code Example
  <pre><code>
import ipdb

db = ipdb.City("/path/to/city.ipv4.ipdb")
# db.reload("/path/to/city.ipv4.ipdb") # update ipdb database file reload data
print(db.is_ipv4(), db.is_ipv6())
print(db.languages()) # support language
print(db.fields()) #  support fields
print(db.build_time()) #  build database time
print(db.find("1.1.1.1", "CN")) #  query ip return array
# print(db.find(u"1.1.1.1", "CN")) #  Python 2.7
print(db.find_map("8.8.8.8", "CN")) #  query ip return dict
print(db.find_info("118.28.1.1", "CN").country_name) 
  </pre></code>

### IPDB Database Fields:
<pre>
country_name : Country Name 
region_name  : Province Name   
city_name    : City Name 
owner_domain : Domain of IP owner
isp_domain  :  ISP of IP being broadcasted
latitude  :  Latitude   
longitude : Longitude    
timezone : Timezone     
utc_offset : UTC time standard offset    
china_admin_code : China administrative divisions code
idd_code : International Dialling Codes 
country_code : Two-letter country codes based on ISO 3166. 
continent_code : Regional Internet registry code.   
idc : IDC label
base_station : Basestation label
country_code3 : Three-letter country codes based on ISO 3166.
european_union : European union label
currency_code : Currency Code    
currency_name : Currency Name
anycast : ANYCAST label      

</pre>

### IPDB CN District sample code :
  <pre>
import ipdb

db = ipdb.District("/path/to/china_district.ipdb")
print(db.is_ipv4(), db.is_ipv6())
print(db.languages())
print(db.fields())
print(db.build_time())
print(db.find("1.12.13.255", "CN"))
print(db.find_map("1.12.13.255", "CN"))
print(db.find_info("1.12.13.255", "CN").country_name)
  </pre>

### IPDB Basestation sample code :
<pre>
import ipdb
db = ipdb.BaseStation("/path/to/base_station.ipdb")
print(db.is_ipv4(), db.is_ipv6())
print(db.languages())
print(db.fields())
print(db.build_time())
print(db.find_map("117.136.83.55", "CN"))
</pre>

================================================
FILE: example.py
================================================
from  __future__ import unicode_literals
import ipdb,sys

import pandas as pd

def test_city_district():
    db = ipdb.City("c:/work/ipdb/test.ipdb")
    print(db.fields())
    city = db.find_info(u"111.199.81.160", "CN")
    qx = city.get_district()
    if qx != None:
        print(qx.city_name, qx.district_name)

def test_free():
    db = ipdb.City("c:/work/ipdb/mydata4vipweek2.ipdb")
    print(db.is_ipv4(), db.is_ipv6())
    print(db.languages())
    print(db.fields())
    print(db.build_time())
    print(db.find("1.1.1.1", "CN"))

    print("ipdb reload", db.reload("c:/work/ipdb/city.free.ipdb"))
    print(db.find("118.28.1.1", "CN"))


    try:
        print(db.find("2000:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF", "CN"))
    except Exception as e:
        print(e)


def test_city_ipv4():
    db = ipdb.City("c:/tiantexin/download/mydata4vipday4_cn.ipdb")
    print(db.is_ipv4(), db.is_ipv6())
    print(db.languages())
    print(db.fields())
    print(db.build_time())
    print(db.find("1.1.1.1", "CN"))
    print(db.find_map("8.8.8.8", "CN"))
    print(db.find_info("118.28.1.1", "CN").country_name)

import  ipaddress

def test_city_ipv6_test():

    db = ipdb.City("c:/work/ipdb/mydata6vipday2.ipdb")

    print(db.find("2001:44c8:4644:1191:3c41:724d:e391:51b0", "CN"))
    print(db.find_map("2a04:3543:1000:2310:ecb3:3eff:fef0:20e1", "CN"))
    print(db.find_info("2a04:3543:1000:2310:ecb3:3eff:fef0:20e1", "CN").country_name)

def test_city_ipv6():
    db4 = ipdb.City("c:/tiantexin/download/mydata4vipday4_cn.ipdb")
    db = ipdb.City("c:/work/ipdb/mydata6vipday2.ipdb")

    df = pd.read_csv("C:\\Users\\GAOCHUNHUI\\Documents\\WeChat Files\\daxime\\FileStorage\\File\\2019-10\\ipiptest\\ip_data.csv")
    for i, row in df.iterrows():
        if ipaddress.ip_address(row['request_ip']).version == 4:

            db4.find(row['request_ip'], "CN")
        else:
            print(db.find(row['request_ip'], "CN"), row['request_ip'])

    try:
        print(db.find("2000:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF", "CN"))
    except Exception as e:
        print(e)


def test_district():
    db = ipdb.District("c:/work/ipdb/china_district.ipdb")
    print(db.is_ipv4(), db.is_ipv6())
    print(db.languages())
    print(db.fields())
    print(db.build_time())
    for A in range(223):
        for B in range (255):
            try:
                print(db.find("%d.%d.114.144" % (A, B), "CN"))
            except ipdb.IPNotFound as e:
                print(e)

    try:
        print(db.find("1.1.1.1", "CN"))
    except ipdb.IPNotFound as e: # ip not found
        print(e)
    except ipdb.DatabaseError as e: # database file size error
        print(e)
    print(db.find_map("1.12.13.255", "CN"))
    print(db.find_info("1.12.13.255", "CN").country_name)


def test_base_station():
    db = ipdb.BaseStation("c:/work/ipdb/base_station.ipdb")
    print(db.is_ipv4(), db.is_ipv6())
    print(db.languages())
    print(db.fields())
    print(db.build_time())
    print(db.find_map("117.136.83.55", "CN"))


def test_idc_list():
    db = ipdb.IDC("c:/work/ipdb/idc_list.ipdb")
    print(db.find_map("1.1.1.1", "CN"))
    print(db.find_map("8.8.8.8", "CN"))

# test_city_ipv4()
# test_city_ipv6_test()
# test_base_station()
test_city_district()
# test_city_ipv4()

================================================
FILE: ipdb/__init__.py
================================================
# -*- coding: utf-8 -*-
"""
    :copyright: ©2018 by IPIP.net
"""

from .city import City
from .district import District
from .idc import IDC
from .base_station import BaseStation
from .exceptions import IPNotFound
from .exceptions import DatabaseError
from .asn import ASNInfo

================================================
FILE: ipdb/asn.py
================================================
# -*- coding: utf-8 -*-
"""
    :copyright: ©2018 by IPIP.net
"""

class ASNInfo:
    asn = -1
    reg = ""
    cc = ""
    net = ""
    org = ""

    def __init__(self, **kwargs):
        self._map = kwargs
        for key in self._map:
            self.__dict__[key] = self._map[key]

    def get_number(self):
        return self.asn

    def get_registry(self):
        return self.reg

    def get_country(self):
        return self.cc

    def get_net_name(self):
        return self.net

    def get_organization(self):
        return self.org


================================================
FILE: ipdb/base_station.py
================================================
# -*- coding: utf-8 -*-
"""
    :copyright: ©2018 by IPIP.net
"""

from .database import Reader


class BaseStationInfo:
    country_name = ""
    region_name = ""
    city_name = ""
    owner_domain = ""
    isp_domain = ""
    base_station = ""

    def __init__(self, **kwargs):
        self._map = kwargs
        for key in self._map:
            self.__dict__[key] = self._map[key]


class BaseStation:

    db = None

    def __init__(self, name):
        self.db = Reader(name)

    def reload(self, name):
        try:
            db = Reader(name)
            self.db = db
            return True
        except:
            return False            

    def find(self, addr, language):
        return self.db.find(addr, language)

    def find_map(self, addr, language):
        return self.db.find_map(addr, language)

    def find_info(self, addr, language):
        m = self.db.find_map(addr, language)
        if m is None:
            return None
        return BaseStationInfo(**m)

    def is_ipv4(self):
        return self.db.is_support_ipv4()

    def is_ipv6(self):
        return self.db.is_support_ipv6()

    def languages(self):
        return self.db.support_languages()

    def fields(self):
        return self.db.support_fields()

    def build_time(self):
        return self.db.build_utc_time()

================================================
FILE: ipdb/city.py
================================================
# -*- coding: utf-8 -*-
"""
    :copyright: ©2018 by IPIP.net
"""

from .database import Reader
from .district import DistrictInfo
from .asn import ASNInfo

import json

class CityInfo:
    country_name = ""
    region_name = ""
    city_name = ""
    district_name = ""
    owner_domain = ""
    isp_domain = ""
    latitude = ""
    longitude = ""
    timezone = ""
    utc_offset = ""
    china_region_code = ""
    china_city_code = ""
    china_district_code = ""
    china_admin_code = ""
    idd_code = ""
    country_code = ""
    continent_code = ""
    idc = ""
    base_station = ""
    country_code3 = ""
    european_union = ""
    currency_code = ""
    currency_name = ""
    anycast = ""
    line = ""
    usage_type = ""
    district_info = ""
    route = ""
    asn = ""
    asn_info = ""

    def __init__(self, **kwargs):
        self._map = kwargs
        for key in self._map:
            self.__dict__[key] = self._map[key]

    def get_district(self):
        if len(self.district_info) == 0:
            return None
        o = json.loads(self.district_info)
        o["country_name"] = self.country_name
        o["region_name"] = self.region_name
        o["city_name"] = self.city_name
        return DistrictInfo(**o)

    def get_asninfo(self):
        if len(self.asn_info) == 0:
            return None
        ls = json.loads(self.asn_info)
        result = []
        for i in ls:
            result.append(ASNInfo(**i))

        return result


class City:

    db = None

    def __init__(self, name):
        self.db = Reader(name)

    def reload(self, name):
        try:
            db = Reader(name)
            self.db = db
            return True
        except:
            return False            

    def find(self, addr, language):
        return self.db.find(addr, language)

    def find_map(self, addr, language):
        return self.db.find_map(addr, language)

    def find_info(self, addr, language):
        m = self.db.find_map(addr, language)
        if m is None:
            return None
        return CityInfo(**m)

    def is_ipv4(self):
        return self.db.is_support_ipv4()

    def is_ipv6(self):
        return self.db.is_support_ipv6()

    def languages(self):
        return self.db.support_languages()

    def fields(self):
        return self.db.support_fields()

    def build_time(self):
        return self.db.build_utc_time()


================================================
FILE: ipdb/database.py
================================================
# -*- coding: utf-8 -*-
"""
    :copyright: ©2018 by IPIP.net
"""

import ipaddress
import json
import sys

from .util import bytes2long
from .exceptions import NoSupportIPv4Error, NoSupportIPv6Error, NoSupportLanguageError, DatabaseError, IPNotFound


class MetaData(object):
    def __init__(self, **kwargs):
        self.fields = kwargs['fields']
        self.node_count = kwargs['node_count']
        self.total_size = kwargs['total_size']
        self.build = kwargs['build']
        self.languages = kwargs['languages']
        self.ip_version = kwargs['ip_version']


class Reader:

    _meta = {}
    data = b""

    _v4offset = 0
    _v6offsetCache = {}

    def __init__(self, name):
        self._v4offset = 0
        self._v6offsetCache = {}

        file = open(name, "rb")
        self.data = file.read()
        self._file_size = len(self.data)
        file.close()
        meta_length = bytes2long(self.data[0], self.data[1], self.data[2], self.data[3])
        if sys.version_info < (3,0):
            meta = json.loads(str(self.data[4:meta_length + 4]))
        else:
            meta = json.loads(str(self.data[4:meta_length + 4], 'utf-8'))

        self._meta = MetaData(**meta)
        if len(self._meta.languages) == 0 or len(self._meta.fields) == 0:
            raise DatabaseError("database meta error")
        if self._file_size != (4 + meta_length + self._meta.total_size):
            raise DatabaseError("database size error")

        self.data = self.data[4+meta_length:]

    def _read_node(self, node, idx):
        off = idx * 4 + node * 8
        return bytes2long(self.data[off], self.data[off + 1], self.data[off + 2], self.data[off + 3])

    def _find_node(self, ip):

        if ip.version == 6:
            bit_count = 128
        else:
            bit_count = 32

        idx = 0
        node = 0
        key = ip.packed[0:2]
        if bit_count == 32:
            if self._v4offset == 0:
                i = 0
                while i < 96:
                    if i >= 80:
                        node = self._read_node(node, 1)
                    else:
                        node = self._read_node(node, 0)
                    i += 1
                self._v4offset = node
            else:
                node = self._v4offset
        else:
            val = self._v6offsetCache.get(key, -1)
            if val > -1:
                idx = 16
                node = val

        packed = bytearray(ip.packed)
        while idx < bit_count:
            if node > self._meta.node_count:
                break
            node = self._read_node(node, (1 & (packed[idx >> 3] >> 7 - (idx % 8))))
            idx += 1
            if idx == 16 and bit_count == 128:
                self._v6offsetCache[key] = node

        if node > self._meta.node_count:
            return node
        raise IPNotFound("ip not found")

    def _resolve(self, node):
        resolved = node - self._meta.node_count + self._meta.node_count * 8
        size = bytes2long(0, 0, self.data[resolved], self.data[resolved + 1])
        if (resolved+2+size) > len(self.data):
            raise DatabaseError("database is error")
        return self.data[resolved+2:resolved+2+size]

    def find(self, addr, language):
        off = self._meta.languages.get(language)
        if off is None:
            raise NoSupportLanguageError(language + " is not support")

        ipv = ipaddress.ip_address(addr)
        if ipv.version == 6:
            if self.is_support_ipv6() is False:
                raise NoSupportIPv6Error("database is not support ipv6")
        elif ipv.version == 4:
            if self.is_support_ipv4() is False:
                raise NoSupportIPv4Error("database is not support ipv4")

        node = self._find_node(ipv)
        if node is None:
            return None

        bs = self._resolve(node)
        if bs is None:
            return None

        tmp = bs.decode("utf-8").split("\t")
        end = off + len(self._meta.fields)
        if len(tmp) < end:
            raise DatabaseError("database is error")

        return tmp[off:off+len(self._meta.fields)]

    def find_map(self, addr, language):
        loc = self.find(addr, language)
        if loc is None:
            return None
        m = {}
        for idx, value in enumerate(self._meta.fields):
            m[value] = loc[idx]
        return m


    def get_meta_data(self):
        return self._meta

    def support_languages(self):
        ls = []
        for p in self._meta.languages:
            ls.append(p)
        return ls

    def support_fields(self):
        return self._meta.fields

    def is_support_ipv4(self):
        return (self._meta.ip_version & 0x01) == 0x01

    def is_support_ipv6(self):
        return (self._meta.ip_version & 0x02) == 0x02

    def build_utc_time(self):
        return self._meta.build


================================================
FILE: ipdb/district.py
================================================
# -*- coding: utf-8 -*-
"""
    :copyright: ©2018 by IPIP.net
"""

from .database import Reader


class DistrictInfo:
    country_name = ""
    region_name = ""
    city_name = ""
    district_name = ""
    china_admin_code = ""
    covering_radius = ""
    latitude = ""
    longitude = ""

    def __init__(self, **kwargs):
        self._map = kwargs
        for key in self._map:
            self.__dict__[key] = self._map[key]


class District:

    db = None

    def __init__(self, name):
        self.db = Reader(name)

    def reload(self, name):
        try:
            db = Reader(name)
            self.db = db
            return True
        except:
            return False            

    def find(self, addr, language):
        return self.db.find(addr, language)

    def find_map(self, addr, language):
        return self.db.find_map(addr, language)

    def find_info(self, addr, language):
        m = self.db.find_map(addr, language)
        if m is None:
            return None
        return DistrictInfo(**m)

    def is_ipv4(self):
        return self.db.is_support_ipv4()

    def is_ipv6(self):
        return self.db.is_support_ipv6()

    def languages(self):
        return self.db.support_languages()

    def fields(self):
        return self.db.support_fields()

    def build_time(self):
        return self.db.build_utc_time()

================================================
FILE: ipdb/exceptions.py
================================================
# -*- coding: utf-8 -*-
"""
    :copyright: ©2018 by IPIP.net
"""


class DatabaseError(Exception):
    pass

class NoSupportLanguageError(Exception):
    pass

class NoSupportIPv6Error(Exception):
    pass

class NoSupportIPv4Error(Exception):
    pass

class IPNotFound(Exception):
    pass

================================================
FILE: ipdb/idc.py
================================================
# -*- coding: utf-8 -*-
"""
    :copyright: ©2018 by IPIP.net
"""

from .database import Reader


class IDCInfo:
    country_name = ""
    region_name = ""
    city_name = ""
    owner_domain = ""
    isp_domain = ""
    idc = ""

    def __init__(self, **kwargs):
        self._map = kwargs
        for key in self._map:
            self.__dict__[key] = self._map[key]


class IDC:

    db = None

    def __init__(self, name):
        self.db = Reader(name)

    def reload(self, name):
        try:
            db = Reader(name)
            self.db = db
            return True
        except:
            return False

    def find(self, addr, language):
        return self.db.find(addr, language)

    def find_map(self, addr, language):
        return self.db.find_map(addr, language)

    def find_info(self, addr, language):
        m = self.db.find_map(addr, language)
        if m is None:
            return None
        return IDCInfo(**m)

    def is_ipv4(self):
        return self.db.is_support_ipv4()

    def is_ipv6(self):
        return self.db.is_support_ipv6()

    def languages(self):
        return self.db.support_languages()

    def fields(self):
        return self.db.support_fields()

    def build_time(self):
        return self.db.build_utc_time()

================================================
FILE: ipdb/util.py
================================================
# -*- coding: utf-8 -*-
"""
    :copyright: ©2018 by IPIP.net
"""


import sys


def bytes2long(a, b, c, d):
    return convert(a) << 24 | convert(b) << 16 | convert(c) << 8 | convert(d)


def convert(v):
    if v == "" or v == 0:
        return 0
    if sys.version_info.major >= 3:
        return v
    else:
        return ord(v)


================================================
FILE: ipdb_test.py
================================================
import unittest

import ipdb

class TestIPDb(unittest.TestCase):

    def test_city(self):
        print("\n\ntest city start\n\n")
        city = ipdb.City("c:/work/ipdb/city.ipv4.ipdb")
        print("ipdb.build.time:", city.build_time())
        for A in range(224):
            ip_address = u"%d.28.1.1" % A
            print(ip_address, city.find(ip_address, "CN"))
            print(ip_address, city.find_map(ip_address, "CN"))
            print(ip_address, city.find_info(ip_address, "CN"))

        print("\n\ntest city start\n\n")

    def test_district(self):
        print("\n\ntest district start\n\n")
        district = ipdb.District("c:/work/ipdb/china_district.ipdb")
        print("ipdb.build.time:", district.build_time())
        for A in range(224):
            ip_address = u"%d.28.1.1" % A
            try:
                print(ip_address, district.find(ip_address, "CN"))
                print(ip_address, district.find_map(ip_address, "CN"))
                print(ip_address, district.find_info(ip_address, "CN"))
            except ipdb.IPNotFound as e:
                print(ip_address, e)
        print("\n\ntest district end\n\n")

    def test_station(self):
        print("\n\ntest base_station start\n\n")
        base_station = ipdb.BaseStation("c:/work/ipdb/base_station.ipdb")
        print("ipdb.build.time:", base_station.build_time())
        for A in range(224):
            ip_address = u"%d.28.1.1" % A
            try:
                print(ip_address, base_station.find(ip_address, "CN"))
                print(ip_address, base_station.find_map(ip_address, "CN"))
                print(ip_address, base_station.find_info(ip_address, "CN"))
            except ipdb.IPNotFound as e:
                print(ip_address, e)
        print("\n\ntest base_station end\n\n")


if __name__ == "__main__":
    unittest.main()

================================================
FILE: setup.py
================================================
# coding=utf-8

from setuptools import setup

setup(
    name='ipip-ipdb',
    version="1.6.0",
    description=(
        'IPIP.net officially supported IP database ipdb format parsing library'
    ),
    author='IPIP.net',
    author_email='frk@ipip.net',
    maintainer='frk',
    maintainer_email='frk@ipip.net',
    license='Apache License Version 2.0',
    packages=['ipdb'],
    platforms=["all"],
    url='https://github.com/ipipdotnet/ipdb-python',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Operating System :: OS Independent',
        'Intended Audience :: Developers',
        'Programming Language :: Python',
        'Programming Language :: Python :: Implementation',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Software Development :: Libraries'
    ],
)
Download .txt
gitextract_54w2ubn7/

├── .gitignore
├── LICENSE
├── README.md
├── README_en.md
├── example.py
├── ipdb/
│   ├── __init__.py
│   ├── asn.py
│   ├── base_station.py
│   ├── city.py
│   ├── database.py
│   ├── district.py
│   ├── exceptions.py
│   ├── idc.py
│   └── util.py
├── ipdb_test.py
└── setup.py
Download .txt
SYMBOL INDEX (95 symbols across 10 files)

FILE: example.py
  function test_city_district (line 6) | def test_city_district():
  function test_free (line 14) | def test_free():
  function test_city_ipv4 (line 32) | def test_city_ipv4():
  function test_city_ipv6_test (line 44) | def test_city_ipv6_test():
  function test_city_ipv6 (line 52) | def test_city_ipv6():
  function test_district (line 70) | def test_district():
  function test_base_station (line 93) | def test_base_station():
  function test_idc_list (line 102) | def test_idc_list():

FILE: ipdb/asn.py
  class ASNInfo (line 6) | class ASNInfo:
    method __init__ (line 13) | def __init__(self, **kwargs):
    method get_number (line 18) | def get_number(self):
    method get_registry (line 21) | def get_registry(self):
    method get_country (line 24) | def get_country(self):
    method get_net_name (line 27) | def get_net_name(self):
    method get_organization (line 30) | def get_organization(self):

FILE: ipdb/base_station.py
  class BaseStationInfo (line 9) | class BaseStationInfo:
    method __init__ (line 17) | def __init__(self, **kwargs):
  class BaseStation (line 23) | class BaseStation:
    method __init__ (line 27) | def __init__(self, name):
    method reload (line 30) | def reload(self, name):
    method find (line 38) | def find(self, addr, language):
    method find_map (line 41) | def find_map(self, addr, language):
    method find_info (line 44) | def find_info(self, addr, language):
    method is_ipv4 (line 50) | def is_ipv4(self):
    method is_ipv6 (line 53) | def is_ipv6(self):
    method languages (line 56) | def languages(self):
    method fields (line 59) | def fields(self):
    method build_time (line 62) | def build_time(self):

FILE: ipdb/city.py
  class CityInfo (line 12) | class CityInfo:
    method __init__ (line 44) | def __init__(self, **kwargs):
    method get_district (line 49) | def get_district(self):
    method get_asninfo (line 58) | def get_asninfo(self):
  class City (line 69) | class City:
    method __init__ (line 73) | def __init__(self, name):
    method reload (line 76) | def reload(self, name):
    method find (line 84) | def find(self, addr, language):
    method find_map (line 87) | def find_map(self, addr, language):
    method find_info (line 90) | def find_info(self, addr, language):
    method is_ipv4 (line 96) | def is_ipv4(self):
    method is_ipv6 (line 99) | def is_ipv6(self):
    method languages (line 102) | def languages(self):
    method fields (line 105) | def fields(self):
    method build_time (line 108) | def build_time(self):

FILE: ipdb/database.py
  class MetaData (line 14) | class MetaData(object):
    method __init__ (line 15) | def __init__(self, **kwargs):
  class Reader (line 24) | class Reader:
    method __init__ (line 32) | def __init__(self, name):
    method _read_node (line 54) | def _read_node(self, node, idx):
    method _find_node (line 58) | def _find_node(self, ip):
    method _resolve (line 99) | def _resolve(self, node):
    method find (line 106) | def find(self, addr, language):
    method find_map (line 134) | def find_map(self, addr, language):
    method get_meta_data (line 144) | def get_meta_data(self):
    method support_languages (line 147) | def support_languages(self):
    method support_fields (line 153) | def support_fields(self):
    method is_support_ipv4 (line 156) | def is_support_ipv4(self):
    method is_support_ipv6 (line 159) | def is_support_ipv6(self):
    method build_utc_time (line 162) | def build_utc_time(self):

FILE: ipdb/district.py
  class DistrictInfo (line 9) | class DistrictInfo:
    method __init__ (line 19) | def __init__(self, **kwargs):
  class District (line 25) | class District:
    method __init__ (line 29) | def __init__(self, name):
    method reload (line 32) | def reload(self, name):
    method find (line 40) | def find(self, addr, language):
    method find_map (line 43) | def find_map(self, addr, language):
    method find_info (line 46) | def find_info(self, addr, language):
    method is_ipv4 (line 52) | def is_ipv4(self):
    method is_ipv6 (line 55) | def is_ipv6(self):
    method languages (line 58) | def languages(self):
    method fields (line 61) | def fields(self):
    method build_time (line 64) | def build_time(self):

FILE: ipdb/exceptions.py
  class DatabaseError (line 7) | class DatabaseError(Exception):
  class NoSupportLanguageError (line 10) | class NoSupportLanguageError(Exception):
  class NoSupportIPv6Error (line 13) | class NoSupportIPv6Error(Exception):
  class NoSupportIPv4Error (line 16) | class NoSupportIPv4Error(Exception):
  class IPNotFound (line 19) | class IPNotFound(Exception):

FILE: ipdb/idc.py
  class IDCInfo (line 9) | class IDCInfo:
    method __init__ (line 17) | def __init__(self, **kwargs):
  class IDC (line 23) | class IDC:
    method __init__ (line 27) | def __init__(self, name):
    method reload (line 30) | def reload(self, name):
    method find (line 38) | def find(self, addr, language):
    method find_map (line 41) | def find_map(self, addr, language):
    method find_info (line 44) | def find_info(self, addr, language):
    method is_ipv4 (line 50) | def is_ipv4(self):
    method is_ipv6 (line 53) | def is_ipv6(self):
    method languages (line 56) | def languages(self):
    method fields (line 59) | def fields(self):
    method build_time (line 62) | def build_time(self):

FILE: ipdb/util.py
  function bytes2long (line 10) | def bytes2long(a, b, c, d):
  function convert (line 14) | def convert(v):

FILE: ipdb_test.py
  class TestIPDb (line 5) | class TestIPDb(unittest.TestCase):
    method test_city (line 7) | def test_city(self):
    method test_district (line 19) | def test_district(self):
    method test_station (line 33) | def test_station(self):
Condensed preview — 16 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (38K chars).
[
  {
    "path": ".gitignore",
    "chars": 1208,
    "preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n.idea\n# Distribution / pa"
  },
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 2168,
    "preview": "# ipdb-python\nIPIP.net officially supported IP database ipdb format parsing library\n\n# Python Parse ipdb file\n\n## Instal"
  },
  {
    "path": "README_en.md",
    "chars": 2201,
    "preview": "# ipdb-python\nIPIP.net officially supported IP database ipdb format parsing library\n\n# Python Parse ipdb file\n\n## Instal"
  },
  {
    "path": "example.py",
    "chars": 3272,
    "preview": "from  __future__ import unicode_literals\nimport ipdb,sys\n\nimport pandas as pd\n\ndef test_city_district():\n    db = ipdb.C"
  },
  {
    "path": "ipdb/__init__.py",
    "chars": 277,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nfrom .city import City\nfrom .district import District"
  },
  {
    "path": "ipdb/asn.py",
    "chars": 551,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nclass ASNInfo:\n    asn = -1\n    reg = \"\"\n    cc = \"\"\n"
  },
  {
    "path": "ipdb/base_station.py",
    "chars": 1326,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nfrom .database import Reader\n\n\nclass BaseStationInfo:"
  },
  {
    "path": "ipdb/city.py",
    "chars": 2404,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nfrom .database import Reader\nfrom .district import Di"
  },
  {
    "path": "ipdb/database.py",
    "chars": 4849,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nimport ipaddress\nimport json\nimport sys\n\nfrom .util i"
  },
  {
    "path": "ipdb/district.py",
    "chars": 1364,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nfrom .database import Reader\n\n\nclass DistrictInfo:\n  "
  },
  {
    "path": "ipdb/exceptions.py",
    "chars": 292,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\n\nclass DatabaseError(Exception):\n    pass\n\nclass NoSu"
  },
  {
    "path": "ipdb/idc.py",
    "chars": 1281,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nfrom .database import Reader\n\n\nclass IDCInfo:\n    cou"
  },
  {
    "path": "ipdb/util.py",
    "chars": 333,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\n\nimport sys\n\n\ndef bytes2long(a, b, c, d):\n    return "
  },
  {
    "path": "ipdb_test.py",
    "chars": 1856,
    "preview": "import unittest\n\nimport ipdb\n\nclass TestIPDb(unittest.TestCase):\n\n    def test_city(self):\n        print(\"\\n\\ntest city "
  },
  {
    "path": "setup.py",
    "chars": 1059,
    "preview": "# coding=utf-8\n\nfrom setuptools import setup\n\nsetup(\n    name='ipip-ipdb',\n    version=\"1.6.0\",\n    description=(\n      "
  }
]

About this extraction

This page contains the full source code of the ipipdotnet/ipdb-python GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 16 files (35.0 KB), approximately 9.2k tokens, and a symbol index with 95 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!