python获取指定IP国家代码信息

     今天在网络编程的时候发现了一个有意思的东西,可以利用http://freegeoip.net/json/ + IP的形式来查询IP来自于哪个国家,利用到 了python的urllib模块,查询之后得到的内容是一个字典,可以使用get方法很容易的获得所需要的信息,代码如下:

#!/usr/bin/python  
# -*- coding: utf-8 -*-  


from urllib import urlopen
from urllib2 import HTTPError
import json
'''
功能:查询制定IPv4或者IPv6地址的国家编码
'''

def getCountry(ipAddress):
    try:
        response = urlopen("http://freegeoip.net/json/"+ipAddress).read().decode('utf-8')
    except HTTPError:
        print None
    responseJson = json.loads(response)
    print ipAddress + '  is coming from  ', responseJson.get("country_code")

if __name__ == '__main__':
	ipAddress = ['97.32.131.205', '216.186.131.29', '116.58.205.165', '43.252.233.5', '2607:fb90:5223:c275:0:17:a6be:ca01', 
	'162.247.124.52', '68.8.169.121', '202.53.87.74', '66.87.64.75', '213.55.95.160']
	for one_ip in ipAddress:
		getCountry(one_ip)
下面是运行结果:

97.32.131.205  is coming from   US
216.186.131.29  is coming from   US
116.58.205.165  is coming from   BD
43.252.233.5  is coming from   MY
2607:fb90:5223:c275:0:17:a6be:ca01  is coming from   US
162.247.124.52  is coming from   CA
68.8.169.121  is coming from   US
202.53.87.74  is coming from   IN
66.87.64.75  is coming from   US
213.55.95.160  is coming from   ET

你可能感兴趣的:(python获取指定IP国家代码信息)