Python code for accessing a pure IP database

Source: Internet
Author: User

Core code: Copy codeThe Code is as follows :#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-

From bisect import bisect

_ LIST1, _ LIST2 = [], []
_ INIT = False

Ip2int = lambda ip_str: reduce (lambda a, B: (a <8) + B, [int (I) for I in ip_str.split ('.')])

Def _ init ():
Global _ LIST, _ INIT
If not _ INIT:
For l in open('ipdata.txt ', 'rb '):
Ip1, ip2 = l. split () [: 2]
Addr = ''. join (l. split () [2:])
Ip1, ip2 = ip2int (ip1), ip2int (ip2)
_ LIST1.append (ip1)
_ LIST2.append (ip1, ip2, addr ))
_ INIT = True

Def ip_from (ip ):
_ Init ()
I = ip2int (ip)
Idx = bisect (_ LIST1, I)
Assert (idx> 0)
If len (_ LIST1) <= idx:
Return u 'unknown ip address % s' % ip
Else:
Frm, to, addr = _ LIST2 [idx-1]
If frm <= I <=:
Return addr
Else:
Return u 'unknown ip address % s' % ip

If _ name _ = '_ main __':
Print ip_from ('2014. 238.54.106 ')
Print ip_from ('1970. 181.29.160 ')
Print ip_from ('2014. 238.54.107 ')
Print ip_from ('8. 8.8.8 ')

Code package download http://xiazai.jb51.net/201105/yuanma/ipaddress.7z

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.