代码:
#coding:utf-8
import requests
import json
import socket
import re,urllib2
def get_my_ip1():
my_ip1 = socket.gethostbyname(socket.gethostname())
print(u'您的外(公)网/内网ip是:' + my_ip1)
def get_my_ip2():
url1 = 'http://ip.chinaz.com/'
url2 = 'http://www.whereismyip.com/'
my_ip2 = ''
try:
opener = urllib2.urlopen(url1,timeout=10)
if url1 == opener.geturl():
html = opener.read()
my_ip2 = re.search('\d+\.\d+\.\d+\.\d+',html).group(0)
except:
try:
opener = urllib2.urlopen(url2,timeout=15)
if url2 == opener.geturl():
html = opener.read()
my_ip2 = re.search('\d+\.\d+\.\d+\.\d+',html).group(0)
except:
print(u'联网查询外网ip失败...')
my_ip2 = 'None'
if my_ip2 != 'None':
print(u'您的外(公)网ip是:' + my_ip2)
get_ip_physical_location(my_ip2)
def get_ip_physical_location(ip):
print(u'正在查询该ip的物理地址...')
url = 'http://ip.taobao.com/service/getIpInfo.php?ip=' + ip
ip_data = requests.get(url).text
ip_dict = json.loads(ip_data)
if ip_dict.get('code'): #当code的值为非0时
print(u'您输入的ip地址格式有误,请仔细检查。')
else:
data = ip_dict.get('data')
country = data.get('country')
region = data.get('region')
city = data.get('city')
print(u'物理位置: ' + country + region + city)
if __name__ == '__main__':
print(u'正在本地查询您的外网ip地址,如果您是拨号上网则此ip为内网ip...')
get_my_ip1()
print(u'正在联网查询您的外网ip地址...')
get_my_ip2()
while True:
print u'请输入您要查询ip地址(输入q退出):',
ip = raw_input()
if ip == 'q':
print(u'正在退出...')
break
else:
get_ip_physical_location(ip)
Comments | NOTHING