21

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

4

8 回答 8

13

这将获取您的远程 IP 地址

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

如果您不想依赖其他人,则只需上传类似以下 PHP 脚本的内容:

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

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

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

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

于 2008-10-03T12:22:07.410 回答
12

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

只需运行即可解析requests.get("https://api.ipify.org/?format=json").json()['ip']

于 2016-07-18T12:23:19.677 回答
6

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

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

但是,是的,如果不依赖网络本身之外的东西,就不可能轻易做到这一点。

于 2008-10-03T12:25:55.593 回答
5
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))

参考

于 2017-11-29T08:44:59.323 回答
4

如果您不介意脏话,请尝试:

http://wtfismyip.com/json

正如其他人所展示的那样,将它绑定在通常的 urllib 东西中。

还有:

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

于 2013-04-30T16:10:35.870 回答
3
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']

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

于 2016-04-04T15:20:27.213 回答
1

这很简单

>>> import urllib
>>> urllib.urlopen('http://icanhazip.com/').read().strip('\n')
'xx.xx.xx.xx'
于 2016-07-18T21:07:25.763 回答
0

您还可以使用 DNS,它在某些情况下可能比 http 方法更可靠:

#!/usr/bin/env python3

import dns.resolver

resolver1_opendns_ip = False
resolver = dns.resolver.Resolver()
opendns_result = resolver.resolve("resolver1.opendns.com", "A")
for record in opendns_result:
    resolver1_opendns_ip = record.to_text()

if resolver1_opendns_ip:
    resolver.nameservers = [resolver1_opendns_ip]
    myip_result = resolver.resolve("myip.opendns.com", "A")
    for record in myip_result:
        print(f"Your external ip is {record.to_text()}")

这是python的等价物dig +short -4 myip.opendns.com @resolver1.opendns.com

于 2022-02-11T00:34:38.807 回答