[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n.idea\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# ipdb-python\nIPIP.net officially supported IP database ipdb format parsing library\n\n# Python Parse ipdb file\n\n## Installing\n<pre>\n<code>pip install ipip-ipdb</code>\n</pre>\n\n## Dependents ( python 2.x or before python 3.3 )\n<pre><code>pip install ipaddress</code></pre>\n\n## Code Example\n### 适用于IPDB格式\n  <pre><code>\nimport ipdb\n\ndb = ipdb.City(\"/path/to/city.ipv4.ipdb\")\n# db.reload(\"/path/to/city.ipv4.ipdb\") # update ipdb database file reload data\nprint(db.is_ipv4(), db.is_ipv6())\nprint(db.languages()) # support language\nprint(db.fields()) #  support fields\nprint(db.build_time()) #  build database time\nprint(db.find(\"1.1.1.1\", \"CN\")) #  query ip return array\n# print(db.find(u\"1.1.1.1\", \"CN\")) #  Python 2.7\nprint(db.find_map(\"8.8.8.8\", \"CN\")) #  query ip return dict\nprint(db.find_info(\"118.28.1.1\", \"CN\").country_name) \ndb.find_info(\"118.28.1.1\", \"CN\").get_asninfo()\n  </pre></code>\n\n### 地级市精度库数据字段说明\n<pre>\ncountry_name : 国家名字 \nregion_name  : 省名字   \ncity_name    : 城市名字 \nowner_domain : 所有者   \nisp_domain  : 运营商 \nlatitude  :  纬度 \nlongitude : 经度   \ntimezone : 时区   \nutc_offset : UTC时区    \nchina_admin_code : 中国行政区划代码\nidd_code : 国家电话号码前缀 \ncountry_code : 国家2位代码\ncontinent_code : 大洲代码 \nidc : IDC |  VPN   \nbase_station : 基站 | WIFI\ncountry_code3 : 国家3位代码 \neuropean_union : 是否为欧盟成员国： 1 | 0 \ncurrency_code : 当前国家货币代码  \ncurrency_name : 当前国家货币名称   \nanycast : ANYCAST     \n</pre>\n\n### 适用于IPDB格式的中国地区 IPv4 区县库\n  <pre>\nimport ipdb\n\ndb = ipdb.District(\"/path/to/china_district.ipdb\")\nprint(db.is_ipv4(), db.is_ipv6())\nprint(db.languages())\nprint(db.fields())\nprint(db.build_time())\nprint(db.find(\"1.12.13.255\", \"CN\"))\nprint(db.find_map(\"1.12.13.255\", \"CN\"))\nprint(db.find_info(\"1.12.13.255\", \"CN\").country_name)\n  </pre>\n\n### 适用于IPDB格式的 IDC 库\n<pre>\nimport ipdb\n>>> db = ipdb.IDC(\"/path/to/idc_list.ipdb\") \n>>> print db.find_info(u\"8.142.10.33\", \"CN\").isp_domain\naliyun.com\n>>> print db.find_info(u\"8.142.10.33\", \"CN\").idc\nIDC\n</pre>\n\n### 适用于IPDB格式的基站 IPv4 库\n<pre>\nimport ipdb\ndb = ipdb.BaseStation(\"/path/to/base_station.ipdb\")\nprint(db.is_ipv4(), db.is_ipv6())\nprint(db.languages())\nprint(db.fields())\nprint(db.build_time())\nprint(db.find_map(\"117.136.83.55\", \"CN\"))\n</pre>\n"
  },
  {
    "path": "README_en.md",
    "content": "# ipdb-python\nIPIP.net officially supported IP database ipdb format parsing library\n\n# Python Parse ipdb file\n\n## Installing\n<pre>\n<code>pip install ipip-ipdb</code>\n</pre>\n\n## Dependents ( python 2.x or before python 3.3 )\n<pre><code>pip install ipaddress</code></pre>\n\n## Code Example\n  <pre><code>\nimport ipdb\n\ndb = ipdb.City(\"/path/to/city.ipv4.ipdb\")\n# db.reload(\"/path/to/city.ipv4.ipdb\") # update ipdb database file reload data\nprint(db.is_ipv4(), db.is_ipv6())\nprint(db.languages()) # support language\nprint(db.fields()) #  support fields\nprint(db.build_time()) #  build database time\nprint(db.find(\"1.1.1.1\", \"CN\")) #  query ip return array\n# print(db.find(u\"1.1.1.1\", \"CN\")) #  Python 2.7\nprint(db.find_map(\"8.8.8.8\", \"CN\")) #  query ip return dict\nprint(db.find_info(\"118.28.1.1\", \"CN\").country_name) \n  </pre></code>\n\n### IPDB Database Fields:\n<pre>\ncountry_name : Country Name \nregion_name  : Province Name   \ncity_name    : City Name \nowner_domain : Domain of IP owner\nisp_domain  :  ISP of IP being broadcasted\nlatitude  :  Latitude   \nlongitude : Longitude    \ntimezone : Timezone     \nutc_offset : UTC time standard offset    \nchina_admin_code : China administrative divisions code\nidd_code : International Dialling Codes \ncountry_code : Two-letter country codes based on ISO 3166. \ncontinent_code : Regional Internet registry code.   \nidc : IDC label\nbase_station : Basestation label\ncountry_code3 : Three-letter country codes based on ISO 3166.\neuropean_union : European union label\ncurrency_code : Currency Code    \ncurrency_name : Currency Name\nanycast : ANYCAST label      \n\n</pre>\n\n### IPDB CN District sample code :\n  <pre>\nimport ipdb\n\ndb = ipdb.District(\"/path/to/china_district.ipdb\")\nprint(db.is_ipv4(), db.is_ipv6())\nprint(db.languages())\nprint(db.fields())\nprint(db.build_time())\nprint(db.find(\"1.12.13.255\", \"CN\"))\nprint(db.find_map(\"1.12.13.255\", \"CN\"))\nprint(db.find_info(\"1.12.13.255\", \"CN\").country_name)\n  </pre>\n\n### IPDB Basestation sample code :\n<pre>\nimport ipdb\ndb = ipdb.BaseStation(\"/path/to/base_station.ipdb\")\nprint(db.is_ipv4(), db.is_ipv6())\nprint(db.languages())\nprint(db.fields())\nprint(db.build_time())\nprint(db.find_map(\"117.136.83.55\", \"CN\"))\n</pre>"
  },
  {
    "path": "example.py",
    "content": "from  __future__ import unicode_literals\nimport ipdb,sys\n\nimport pandas as pd\n\ndef test_city_district():\n    db = ipdb.City(\"c:/work/ipdb/test.ipdb\")\n    print(db.fields())\n    city = db.find_info(u\"111.199.81.160\", \"CN\")\n    qx = city.get_district()\n    if qx != None:\n        print(qx.city_name, qx.district_name)\n\ndef test_free():\n    db = ipdb.City(\"c:/work/ipdb/mydata4vipweek2.ipdb\")\n    print(db.is_ipv4(), db.is_ipv6())\n    print(db.languages())\n    print(db.fields())\n    print(db.build_time())\n    print(db.find(\"1.1.1.1\", \"CN\"))\n\n    print(\"ipdb reload\", db.reload(\"c:/work/ipdb/city.free.ipdb\"))\n    print(db.find(\"118.28.1.1\", \"CN\"))\n\n\n    try:\n        print(db.find(\"2000:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF\", \"CN\"))\n    except Exception as e:\n        print(e)\n\n\ndef test_city_ipv4():\n    db = ipdb.City(\"c:/tiantexin/download/mydata4vipday4_cn.ipdb\")\n    print(db.is_ipv4(), db.is_ipv6())\n    print(db.languages())\n    print(db.fields())\n    print(db.build_time())\n    print(db.find(\"1.1.1.1\", \"CN\"))\n    print(db.find_map(\"8.8.8.8\", \"CN\"))\n    print(db.find_info(\"118.28.1.1\", \"CN\").country_name)\n\nimport  ipaddress\n\ndef test_city_ipv6_test():\n\n    db = ipdb.City(\"c:/work/ipdb/mydata6vipday2.ipdb\")\n\n    print(db.find(\"2001:44c8:4644:1191:3c41:724d:e391:51b0\", \"CN\"))\n    print(db.find_map(\"2a04:3543:1000:2310:ecb3:3eff:fef0:20e1\", \"CN\"))\n    print(db.find_info(\"2a04:3543:1000:2310:ecb3:3eff:fef0:20e1\", \"CN\").country_name)\n\ndef test_city_ipv6():\n    db4 = ipdb.City(\"c:/tiantexin/download/mydata4vipday4_cn.ipdb\")\n    db = ipdb.City(\"c:/work/ipdb/mydata6vipday2.ipdb\")\n\n    df = pd.read_csv(\"C:\\\\Users\\\\GAOCHUNHUI\\\\Documents\\\\WeChat Files\\\\daxime\\\\FileStorage\\\\File\\\\2019-10\\\\ipiptest\\\\ip_data.csv\")\n    for i, row in df.iterrows():\n        if ipaddress.ip_address(row['request_ip']).version == 4:\n\n            db4.find(row['request_ip'], \"CN\")\n        else:\n            print(db.find(row['request_ip'], \"CN\"), row['request_ip'])\n\n    try:\n        print(db.find(\"2000:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF\", \"CN\"))\n    except Exception as e:\n        print(e)\n\n\ndef test_district():\n    db = ipdb.District(\"c:/work/ipdb/china_district.ipdb\")\n    print(db.is_ipv4(), db.is_ipv6())\n    print(db.languages())\n    print(db.fields())\n    print(db.build_time())\n    for A in range(223):\n        for B in range (255):\n            try:\n                print(db.find(\"%d.%d.114.144\" % (A, B), \"CN\"))\n            except ipdb.IPNotFound as e:\n                print(e)\n\n    try:\n        print(db.find(\"1.1.1.1\", \"CN\"))\n    except ipdb.IPNotFound as e: # ip not found\n        print(e)\n    except ipdb.DatabaseError as e: # database file size error\n        print(e)\n    print(db.find_map(\"1.12.13.255\", \"CN\"))\n    print(db.find_info(\"1.12.13.255\", \"CN\").country_name)\n\n\ndef test_base_station():\n    db = ipdb.BaseStation(\"c:/work/ipdb/base_station.ipdb\")\n    print(db.is_ipv4(), db.is_ipv6())\n    print(db.languages())\n    print(db.fields())\n    print(db.build_time())\n    print(db.find_map(\"117.136.83.55\", \"CN\"))\n\n\ndef test_idc_list():\n    db = ipdb.IDC(\"c:/work/ipdb/idc_list.ipdb\")\n    print(db.find_map(\"1.1.1.1\", \"CN\"))\n    print(db.find_map(\"8.8.8.8\", \"CN\"))\n\n# test_city_ipv4()\n# test_city_ipv6_test()\n# test_base_station()\ntest_city_district()\n# test_city_ipv4()"
  },
  {
    "path": "ipdb/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nfrom .city import City\nfrom .district import District\nfrom .idc import IDC\nfrom .base_station import BaseStation\nfrom .exceptions import IPNotFound\nfrom .exceptions import DatabaseError\nfrom .asn import ASNInfo"
  },
  {
    "path": "ipdb/asn.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nclass ASNInfo:\n    asn = -1\n    reg = \"\"\n    cc = \"\"\n    net = \"\"\n    org = \"\"\n\n    def __init__(self, **kwargs):\n        self._map = kwargs\n        for key in self._map:\n            self.__dict__[key] = self._map[key]\n\n    def get_number(self):\n        return self.asn\n\n    def get_registry(self):\n        return self.reg\n\n    def get_country(self):\n        return self.cc\n\n    def get_net_name(self):\n        return self.net\n\n    def get_organization(self):\n        return self.org\n"
  },
  {
    "path": "ipdb/base_station.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nfrom .database import Reader\n\n\nclass BaseStationInfo:\n    country_name = \"\"\n    region_name = \"\"\n    city_name = \"\"\n    owner_domain = \"\"\n    isp_domain = \"\"\n    base_station = \"\"\n\n    def __init__(self, **kwargs):\n        self._map = kwargs\n        for key in self._map:\n            self.__dict__[key] = self._map[key]\n\n\nclass BaseStation:\n\n    db = None\n\n    def __init__(self, name):\n        self.db = Reader(name)\n\n    def reload(self, name):\n        try:\n            db = Reader(name)\n            self.db = db\n            return True\n        except:\n            return False            \n\n    def find(self, addr, language):\n        return self.db.find(addr, language)\n\n    def find_map(self, addr, language):\n        return self.db.find_map(addr, language)\n\n    def find_info(self, addr, language):\n        m = self.db.find_map(addr, language)\n        if m is None:\n            return None\n        return BaseStationInfo(**m)\n\n    def is_ipv4(self):\n        return self.db.is_support_ipv4()\n\n    def is_ipv6(self):\n        return self.db.is_support_ipv6()\n\n    def languages(self):\n        return self.db.support_languages()\n\n    def fields(self):\n        return self.db.support_fields()\n\n    def build_time(self):\n        return self.db.build_utc_time()"
  },
  {
    "path": "ipdb/city.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nfrom .database import Reader\nfrom .district import DistrictInfo\nfrom .asn import ASNInfo\n\nimport json\n\nclass CityInfo:\n    country_name = \"\"\n    region_name = \"\"\n    city_name = \"\"\n    district_name = \"\"\n    owner_domain = \"\"\n    isp_domain = \"\"\n    latitude = \"\"\n    longitude = \"\"\n    timezone = \"\"\n    utc_offset = \"\"\n    china_region_code = \"\"\n    china_city_code = \"\"\n    china_district_code = \"\"\n    china_admin_code = \"\"\n    idd_code = \"\"\n    country_code = \"\"\n    continent_code = \"\"\n    idc = \"\"\n    base_station = \"\"\n    country_code3 = \"\"\n    european_union = \"\"\n    currency_code = \"\"\n    currency_name = \"\"\n    anycast = \"\"\n    line = \"\"\n    usage_type = \"\"\n    district_info = \"\"\n    route = \"\"\n    asn = \"\"\n    asn_info = \"\"\n\n    def __init__(self, **kwargs):\n        self._map = kwargs\n        for key in self._map:\n            self.__dict__[key] = self._map[key]\n\n    def get_district(self):\n        if len(self.district_info) == 0:\n            return None\n        o = json.loads(self.district_info)\n        o[\"country_name\"] = self.country_name\n        o[\"region_name\"] = self.region_name\n        o[\"city_name\"] = self.city_name\n        return DistrictInfo(**o)\n\n    def get_asninfo(self):\n        if len(self.asn_info) == 0:\n            return None\n        ls = json.loads(self.asn_info)\n        result = []\n        for i in ls:\n            result.append(ASNInfo(**i))\n\n        return result\n\n\nclass City:\n\n    db = None\n\n    def __init__(self, name):\n        self.db = Reader(name)\n\n    def reload(self, name):\n        try:\n            db = Reader(name)\n            self.db = db\n            return True\n        except:\n            return False            \n\n    def find(self, addr, language):\n        return self.db.find(addr, language)\n\n    def find_map(self, addr, language):\n        return self.db.find_map(addr, language)\n\n    def find_info(self, addr, language):\n        m = self.db.find_map(addr, language)\n        if m is None:\n            return None\n        return CityInfo(**m)\n\n    def is_ipv4(self):\n        return self.db.is_support_ipv4()\n\n    def is_ipv6(self):\n        return self.db.is_support_ipv6()\n\n    def languages(self):\n        return self.db.support_languages()\n\n    def fields(self):\n        return self.db.support_fields()\n\n    def build_time(self):\n        return self.db.build_utc_time()\n"
  },
  {
    "path": "ipdb/database.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nimport ipaddress\nimport json\nimport sys\n\nfrom .util import bytes2long\nfrom .exceptions import NoSupportIPv4Error, NoSupportIPv6Error, NoSupportLanguageError, DatabaseError, IPNotFound\n\n\nclass MetaData(object):\n    def __init__(self, **kwargs):\n        self.fields = kwargs['fields']\n        self.node_count = kwargs['node_count']\n        self.total_size = kwargs['total_size']\n        self.build = kwargs['build']\n        self.languages = kwargs['languages']\n        self.ip_version = kwargs['ip_version']\n\n\nclass Reader:\n\n    _meta = {}\n    data = b\"\"\n\n    _v4offset = 0\n    _v6offsetCache = {}\n\n    def __init__(self, name):\n        self._v4offset = 0\n        self._v6offsetCache = {}\n\n        file = open(name, \"rb\")\n        self.data = file.read()\n        self._file_size = len(self.data)\n        file.close()\n        meta_length = bytes2long(self.data[0], self.data[1], self.data[2], self.data[3])\n        if sys.version_info < (3,0):\n            meta = json.loads(str(self.data[4:meta_length + 4]))\n        else:\n            meta = json.loads(str(self.data[4:meta_length + 4], 'utf-8'))\n\n        self._meta = MetaData(**meta)\n        if len(self._meta.languages) == 0 or len(self._meta.fields) == 0:\n            raise DatabaseError(\"database meta error\")\n        if self._file_size != (4 + meta_length + self._meta.total_size):\n            raise DatabaseError(\"database size error\")\n\n        self.data = self.data[4+meta_length:]\n\n    def _read_node(self, node, idx):\n        off = idx * 4 + node * 8\n        return bytes2long(self.data[off], self.data[off + 1], self.data[off + 2], self.data[off + 3])\n\n    def _find_node(self, ip):\n\n        if ip.version == 6:\n            bit_count = 128\n        else:\n            bit_count = 32\n\n        idx = 0\n        node = 0\n        key = ip.packed[0:2]\n        if bit_count == 32:\n            if self._v4offset == 0:\n                i = 0\n                while i < 96:\n                    if i >= 80:\n                        node = self._read_node(node, 1)\n                    else:\n                        node = self._read_node(node, 0)\n                    i += 1\n                self._v4offset = node\n            else:\n                node = self._v4offset\n        else:\n            val = self._v6offsetCache.get(key, -1)\n            if val > -1:\n                idx = 16\n                node = val\n\n        packed = bytearray(ip.packed)\n        while idx < bit_count:\n            if node > self._meta.node_count:\n                break\n            node = self._read_node(node, (1 & (packed[idx >> 3] >> 7 - (idx % 8))))\n            idx += 1\n            if idx == 16 and bit_count == 128:\n                self._v6offsetCache[key] = node\n\n        if node > self._meta.node_count:\n            return node\n        raise IPNotFound(\"ip not found\")\n\n    def _resolve(self, node):\n        resolved = node - self._meta.node_count + self._meta.node_count * 8\n        size = bytes2long(0, 0, self.data[resolved], self.data[resolved + 1])\n        if (resolved+2+size) > len(self.data):\n            raise DatabaseError(\"database is error\")\n        return self.data[resolved+2:resolved+2+size]\n\n    def find(self, addr, language):\n        off = self._meta.languages.get(language)\n        if off is None:\n            raise NoSupportLanguageError(language + \" is not support\")\n\n        ipv = ipaddress.ip_address(addr)\n        if ipv.version == 6:\n            if self.is_support_ipv6() is False:\n                raise NoSupportIPv6Error(\"database is not support ipv6\")\n        elif ipv.version == 4:\n            if self.is_support_ipv4() is False:\n                raise NoSupportIPv4Error(\"database is not support ipv4\")\n\n        node = self._find_node(ipv)\n        if node is None:\n            return None\n\n        bs = self._resolve(node)\n        if bs is None:\n            return None\n\n        tmp = bs.decode(\"utf-8\").split(\"\\t\")\n        end = off + len(self._meta.fields)\n        if len(tmp) < end:\n            raise DatabaseError(\"database is error\")\n\n        return tmp[off:off+len(self._meta.fields)]\n\n    def find_map(self, addr, language):\n        loc = self.find(addr, language)\n        if loc is None:\n            return None\n        m = {}\n        for idx, value in enumerate(self._meta.fields):\n            m[value] = loc[idx]\n        return m\n\n\n    def get_meta_data(self):\n        return self._meta\n\n    def support_languages(self):\n        ls = []\n        for p in self._meta.languages:\n            ls.append(p)\n        return ls\n\n    def support_fields(self):\n        return self._meta.fields\n\n    def is_support_ipv4(self):\n        return (self._meta.ip_version & 0x01) == 0x01\n\n    def is_support_ipv6(self):\n        return (self._meta.ip_version & 0x02) == 0x02\n\n    def build_utc_time(self):\n        return self._meta.build\n"
  },
  {
    "path": "ipdb/district.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nfrom .database import Reader\n\n\nclass DistrictInfo:\n    country_name = \"\"\n    region_name = \"\"\n    city_name = \"\"\n    district_name = \"\"\n    china_admin_code = \"\"\n    covering_radius = \"\"\n    latitude = \"\"\n    longitude = \"\"\n\n    def __init__(self, **kwargs):\n        self._map = kwargs\n        for key in self._map:\n            self.__dict__[key] = self._map[key]\n\n\nclass District:\n\n    db = None\n\n    def __init__(self, name):\n        self.db = Reader(name)\n\n    def reload(self, name):\n        try:\n            db = Reader(name)\n            self.db = db\n            return True\n        except:\n            return False            \n\n    def find(self, addr, language):\n        return self.db.find(addr, language)\n\n    def find_map(self, addr, language):\n        return self.db.find_map(addr, language)\n\n    def find_info(self, addr, language):\n        m = self.db.find_map(addr, language)\n        if m is None:\n            return None\n        return DistrictInfo(**m)\n\n    def is_ipv4(self):\n        return self.db.is_support_ipv4()\n\n    def is_ipv6(self):\n        return self.db.is_support_ipv6()\n\n    def languages(self):\n        return self.db.support_languages()\n\n    def fields(self):\n        return self.db.support_fields()\n\n    def build_time(self):\n        return self.db.build_utc_time()"
  },
  {
    "path": "ipdb/exceptions.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\n\nclass DatabaseError(Exception):\n    pass\n\nclass NoSupportLanguageError(Exception):\n    pass\n\nclass NoSupportIPv6Error(Exception):\n    pass\n\nclass NoSupportIPv4Error(Exception):\n    pass\n\nclass IPNotFound(Exception):\n    pass"
  },
  {
    "path": "ipdb/idc.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\n    :copyright: ©2018 by IPIP.net\n\"\"\"\n\nfrom .database import Reader\n\n\nclass IDCInfo:\n    country_name = \"\"\n    region_name = \"\"\n    city_name = \"\"\n    owner_domain = \"\"\n    isp_domain = \"\"\n    idc = \"\"\n\n    def __init__(self, **kwargs):\n        self._map = kwargs\n        for key in self._map:\n            self.__dict__[key] = self._map[key]\n\n\nclass IDC:\n\n    db = None\n\n    def __init__(self, name):\n        self.db = Reader(name)\n\n    def reload(self, name):\n        try:\n            db = Reader(name)\n            self.db = db\n            return True\n        except:\n            return False\n\n    def find(self, addr, language):\n        return self.db.find(addr, language)\n\n    def find_map(self, addr, language):\n        return self.db.find_map(addr, language)\n\n    def find_info(self, addr, language):\n        m = self.db.find_map(addr, language)\n        if m is None:\n            return None\n        return IDCInfo(**m)\n\n    def is_ipv4(self):\n        return self.db.is_support_ipv4()\n\n    def is_ipv6(self):\n        return self.db.is_support_ipv6()\n\n    def languages(self):\n        return self.db.support_languages()\n\n    def fields(self):\n        return self.db.support_fields()\n\n    def build_time(self):\n        return self.db.build_utc_time()"
  },
  {
    "path": "ipdb/util.py",
    "content": "# -*- 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 convert(a) << 24 | convert(b) << 16 | convert(c) << 8 | convert(d)\n\n\ndef convert(v):\n    if v == \"\" or v == 0:\n        return 0\n    if sys.version_info.major >= 3:\n        return v\n    else:\n        return ord(v)\n"
  },
  {
    "path": "ipdb_test.py",
    "content": "import unittest\n\nimport ipdb\n\nclass TestIPDb(unittest.TestCase):\n\n    def test_city(self):\n        print(\"\\n\\ntest city start\\n\\n\")\n        city = ipdb.City(\"c:/work/ipdb/city.ipv4.ipdb\")\n        print(\"ipdb.build.time:\", city.build_time())\n        for A in range(224):\n            ip_address = u\"%d.28.1.1\" % A\n            print(ip_address, city.find(ip_address, \"CN\"))\n            print(ip_address, city.find_map(ip_address, \"CN\"))\n            print(ip_address, city.find_info(ip_address, \"CN\"))\n\n        print(\"\\n\\ntest city start\\n\\n\")\n\n    def test_district(self):\n        print(\"\\n\\ntest district start\\n\\n\")\n        district = ipdb.District(\"c:/work/ipdb/china_district.ipdb\")\n        print(\"ipdb.build.time:\", district.build_time())\n        for A in range(224):\n            ip_address = u\"%d.28.1.1\" % A\n            try:\n                print(ip_address, district.find(ip_address, \"CN\"))\n                print(ip_address, district.find_map(ip_address, \"CN\"))\n                print(ip_address, district.find_info(ip_address, \"CN\"))\n            except ipdb.IPNotFound as e:\n                print(ip_address, e)\n        print(\"\\n\\ntest district end\\n\\n\")\n\n    def test_station(self):\n        print(\"\\n\\ntest base_station start\\n\\n\")\n        base_station = ipdb.BaseStation(\"c:/work/ipdb/base_station.ipdb\")\n        print(\"ipdb.build.time:\", base_station.build_time())\n        for A in range(224):\n            ip_address = u\"%d.28.1.1\" % A\n            try:\n                print(ip_address, base_station.find(ip_address, \"CN\"))\n                print(ip_address, base_station.find_map(ip_address, \"CN\"))\n                print(ip_address, base_station.find_info(ip_address, \"CN\"))\n            except ipdb.IPNotFound as e:\n                print(ip_address, e)\n        print(\"\\n\\ntest base_station end\\n\\n\")\n\n\nif __name__ == \"__main__\":\n    unittest.main()"
  },
  {
    "path": "setup.py",
    "content": "# coding=utf-8\n\nfrom setuptools import setup\n\nsetup(\n    name='ipip-ipdb',\n    version=\"1.6.0\",\n    description=(\n        'IPIP.net officially supported IP database ipdb format parsing library'\n    ),\n    author='IPIP.net',\n    author_email='frk@ipip.net',\n    maintainer='frk',\n    maintainer_email='frk@ipip.net',\n    license='Apache License Version 2.0',\n    packages=['ipdb'],\n    platforms=[\"all\"],\n    url='https://github.com/ipipdotnet/ipdb-python',\n    classifiers=[\n        'Development Status :: 4 - Beta',\n        'Operating System :: OS Independent',\n        'Intended Audience :: Developers',\n        'Programming Language :: Python',\n        'Programming Language :: Python :: Implementation',\n        'Programming Language :: Python :: 2',\n        'Programming Language :: Python :: 2.7',\n        'Programming Language :: Python :: 3',\n        'Programming Language :: Python :: 3.4',\n        'Programming Language :: Python :: 3.5',\n        'Programming Language :: Python :: 3.6',\n        'Topic :: Software Development :: Libraries'\n    ],\n)"
  }
]