在 Python 中查找面向公众的 IP 地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/166545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 19:35:49  来源:igfitidea点击:

Finding a public facing IP address in Python?

pythonip-address

提问by UnkwnTech

How can I find the public facing IP for my net work in Python?

如何在 Python 中为我的网络找到面向公众的 IP?

采纳答案by UnkwnTech

This will fetch your remote IP address

这将获取您的远程 IP 地址

import urllib
ip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()

If you don't want to rely on someone else, then just upload something like this PHP script:

如果你不想依赖别人,那么只需上传类似这样的 PHP 脚本:

<?php echo $_SERVER['REMOTE_ADDR']; ?>

and change the URL in the Python or if you prefer ASP:

并更改 Python 中的 URL,或者如果您更喜欢 ASP:

<%
Dim UserIPAddress
UserIPAddress = Request.ServerVariables("REMOTE_ADDR")
%>

Note: I don't know ASP, but I figured it might be useful to have here so I googled.

注意:我不知道 ASP,但我认为在这里可能会有用,所以我用谷歌搜索。

回答by Steve Losh

whatismyip.org is better... it just tosses back the ip as plaintext with no extraneous crap.

whatismyip.org 更好......它只是将 ip 作为纯文本返回,没有多余的废话。

import urllib
ip = urllib.urlopen('http://whatismyip.org').read()

But yeah, it's impossible to do it easily without relying on something outside the network itself.

但是,是的,不依赖网络本身之外的东西就不可能轻松做到。

回答by twig

https://api.ipify.org/?format=jsonis pretty straight forward

https://api.ipify.org/?format=json非常简单

can be parsed by just running requests.get("https://api.ipify.org/?format=json").json()['ip']

可以通过运行来解析 requests.get("https://api.ipify.org/?format=json").json()['ip']

回答by powlo

If you don't mind expletives then try:

如果您不介意咒骂,请尝试:

http://wtfismyip.com/json

http://wtfismyip.com/json

Bind it up in the usual urllib stuff as others have shown.

如其他人所示,将其绑定到通常的 urllib 内容中。

There's also:

还有:

http://www.networksecuritytoolkit.org/nst/tools/ip.php

http://www.networksecuritytoolkit.org/nst/tools/ip.php

回答by Arch Angeles

import urllib2
text = urllib2.urlopen('http://www.whatismyip.org').read()
urlRE=re.findall('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}',text)
urlRE        

['146.148.123.123']

Try putting whatever 'findmyipsite' you can find into a list and iterating through them for comparison. This one seems to work well.

尝试将您能找到的任何 'findmyipsite' 放入一个列表中并遍历它们以进行比较。这个似乎运作良好。

回答by Abhijeet

import requests
r = requests.get(r'http://jsonip.com')
# r = requests.get(r'https://ifconfig.co/json')
ip= r.json()['ip']
print('Your IP is {}'.format(ip))

Reference

参考

回答by loretoparisi

This is simple as

这很简单

>>> import urllib
>>> urllib.urlopen('http://icanhazip.com/').read().strip('\n')
'xx.xx.xx.xx'