最简单的(非Python)的工作解决方案,我能想到的是
wget -q -O- icanhazip.com
我想补充一个很短的Python3解决方案,它利用了http://hostip.info的JSON API的。
from urllib.request import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read().decode('utf-8'))
print(info['ip'])
你当然也可以添加一些错误检查,超时条件和一些便利:
#!/usr/bin/env python3
from urllib.request import urlopen
from urllib.error import URLError
import json
try:
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
print(info['ip'])
except URLError as e:
print(e.reason, end=' ') # e.g. 'timed out'
print('(are you connected to the internet?)')
except KeyboardInterrupt:
pass
相关:编程发现公网IP(http://stackoverflow.com/q/613471/4279) – jfs 2014-02-27 17:23:19