2010-02-22 154 views
31

寻找获取计算机当前外部IP的更好方法#...以下工作,但宁愿不依靠外部网站收集信息...我仅限于使用与Mac OS X 10.5使用Python获取计算机的外部IP地址

import os 
import urllib2 

def check_in(): 

    fqn = os.uname()[1] 
    ext_ip = urllib2.urlopen('http://whatismyip.org').read() 
    print ("Asset: %s " % fqn, "Checking in from IP#: %s " % ext_ip) 
+0

相关:编程发现公网IP(http://stackoverflow.com/q/613471/4279) – jfs 2014-02-27 17:23:19

回答

19

如果您在获取外部IP的路由器后面,恐怕您没有别的选择,只能像您一样使用外部服务。如果路由器本身有一些查询接口,则可以使用它,但该解决方案将非常环境且不可靠。

1

捆绑如果机器是一个防火墙标准Python 2.5.1库那么你的解决方案是一个非常明智的:替代能够查询哪些结束行动的防火墙非常依赖于防火墙的类型(如果可能的话)。

6

如果您认为并且外部来源太不可靠,您可以共享一些不同的服务。对于大多数IP查找的网页,他们需要你刮的HTML,但已经创造了精益页像你脚本的几个人 - 也使他们能够减少在其网站上的点击率:

+1

自动化链接在持续时有用,谢谢 – Anake 2013-05-13 11:47:44

+12

这一个可能是理想的:http://icanhazip.com/ – 2013-06-23 11:12:22

0
ipWebCode = urllib.request.urlopen("http://ip.nefsc.noaa.gov").read().decode("utf8") 
ipWebCode=ipWebCode.split("color=red> ") 
ipWebCode = ipWebCode[1] 
ipWebCode = ipWebCode.split("</font>") 
externalIp = ipWebCode[0] 

这是我为其他程序编写的一小段代码。诀窍是找到一个足够简单的网站,以解剖html不是一个痛苦。

2

我在这里尝试了大部分关于这个问题的其他答案,结果发现大多数使用的服务都是失效的,除了一个。

这里是一个脚本,应该做的伎俩和下载的信息仅有极少量:

#!/usr/bin/env python 

import urllib 
import re 

def get_external_ip(): 
    site = urllib.urlopen("http://checkip.dyndns.org/").read() 
    grab = re.findall('([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)', site) 
    address = grab[0] 
    return address 

if __name__ == '__main__': 
    print(get_external_ip()) 
+0

正则表达式坏了。应该是\ d {1,3}。 – 2013-09-30 17:49:23

0

这里的另一种选择脚本。

def track_ip(): 
    """ 
    Returns Dict with the following keys: 
    - ip 
    - latlong 
    - country 
    - city 
    - user-agent 
    """ 

    conn = httplib.HTTPConnection("www.trackip.net") 
    conn.request("GET", "/ip?json") 
    resp = conn.getresponse() 
    print resp.status, resp.reason 

    if resp.status == 200: 
     ip = json.loads(resp.read()) 
    else: 
     print 'Connection Error: %s' % resp.reason 

    conn.close() 
    return ip 

编辑:不要忘了给出import httplib和JSON

+0

这个答案用于为我工作,但使用conda更新包时会中断,所以我已经放弃了这个答案,以便在http://stackoverflow.com/questions/24508730/finding-network-external中使用更简单的解决方案@Hors Sujet -ip-addresses-using-python – nagordon 2015-07-13 13:09:33

38

我写了一个模块为:ipgetter。 旨在从Internet获取您的外部IP地址。它主要用在NAT后面。它从服务器列表中随机选择您的IP,以最大限度地减少单个服务器上的请求开销。 实际上有44个服务器和测试功能来验证服务器是否返回相同的IP。

https://github.com/phoemur/ipgetter

是这样的:

>>> import ipgetter 
>>> IP = ipgetter.myip() 
>>> print(IP) 
'xxx.xxx.xxx.xxx' 

>>> ipgetter.IPgetter().test() 
Number of servers: 44 
IP's : 
'xxx.xxx.xxx.xxx' = 44 ocurrencies 
+0

很棒! Python 2和3兼容。 – 2014-12-04 02:23:49

+0

好的模块!谢啦! – pinogun 2016-04-20 11:32:47

1
In [1]: import stun 

stun.get_ip_info() 
('Restric NAT', 'xx.xx.xx.xx', 55320) 
0

如果你只是写为自己而不是为一个通用的应用程序,你也许可以找到设置页上的地址为您的路由器,然后从该网页的HTML刮。这对我的SMC路由器工作正常。一个阅读和一个简单的RE搜索,我发现它。

我这样做的特别兴趣是让我知道我的家庭IP地址,当我离家出走时,我可以通过VNC返回。还有几行Python将地址存储在Dropbox中用于外部访问,甚至在发现更改时向我发送电子邮件。我已经预定它会在启动时发生,并在此后每小时发生一次。

1

最简单的(非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 
1

在我看来,最简单的解决方法是

f = requests.request('GET', 'http://myip.dnsomatic.com') 
    ip = f.text 

这就是所有。

+0

这可能是值得一提的,你需要'导入请求'。请参阅https://pypi.python.org/pypi/requests – John 2015-09-11 15:19:28

+0

由于“[请求](https://pypi.python.org/pypi/requests)正式支持Python 2.6-2.7和3.3- 3.7,并且在PyPy上运行良好。“但是,它对其他人仍然有用。 – Jerod 2017-03-23 15:41:42

0

使用该脚本:

import urllib, json 

data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read()) 
print data["ip"] 

没有JSON:

import urllib, re 

data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1) 
print data 
17

我喜欢的http://ipify.org。他们甚至提供使用其API的Python代码。

# This example requires the requests library be installed. You can learn more 
# about the Requests library here: http://docs.python-requests.org/en/latest/ 

from requests import get 

ip = get('https://api.ipify.org').text 
print 'My public IP address is:', ip 
3

您应该使用UPnP protocol来查询您的路由器的这些信息。最重要的是,这不依赖于外部服务,这个问题的所有其他答案似乎表明。

有一个叫做miniupnp的Python库可以做到这一点, https://github.com/miniupnp/miniupnp/blob/master/miniupnpc/testupnpigd.py#L52。根据他们的例子中,你应该能够做这样的事情:

import miniupnpc 

u = miniupnpc.UPnP() 
u.discoverdelay = 200; 
u.discover() 
u.selectigd() 
print 'external ip address:', u.externalipaddress() 
8

Python3,使用不外乎标准库

正如前面提到的,一个可使用的某些种类为了一个external service左右不了发现路由器的外部IP地址。

这里是它是如何与python3完成的,使用不外乎the standard library:

import urllib.request 

external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8') 

print(external_ip) 
2
import requests 
import re 


def getMyExtIp(): 
    try: 
     res = requests.get("http://whatismyip.org") 
     myIp = re.compile('(\d{1,3}\.){3}\d{1,3}').search(res.text).group() 
     if myIp != "": 
      return myIp 
    except: 
     pass 
    return "n/a" 
+0

该死的比使用BeautifulSoup快一点,谢谢 – 2017-10-09 16:59:15

相关问题