使用Python获取机器的外部IP地址

发布于 2024-08-22 15:39:51 字数 328 浏览 7 评论 0原文

正在寻找一种更好的方法来获取机器当前的外部 IP #...下面可以工作,但宁愿不依赖外部站点来收集信息...我仅限于使用与 Mac OS 捆绑在一起的标准 Python 2.5.1 库10.5.x

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)

Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

迷途知返 2024-08-29 15:39:51

我喜欢 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').content.decode('utf8')
print('My public IP address is: {}'.format(ip))

I liked the http://ipify.org. They even provide Python code for using their API.

# 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').content.decode('utf8')
print('My public IP address is: {}'.format(ip))
嘿看小鸭子会跑 2024-08-29 15:39:51

Python3,只使用标准库

如前所述,可以按顺序使用 ident.me 等外部服务发现路由器的外部 IP 地址。

以下是使用 python3 完成的方法,除了使用 标准库之外不使用其他任何东西:

import urllib.request

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

print(external_ip)

根据可用性和客户端偏好,可以返回 IPv4 和 IPv6 地址;仅对 IPv4 使用 https://v4.ident.me/,或 https://v6.ident.me/ 仅适用于 IPv6。

Python3, using nothing else but the standard library

As mentioned before, one can use an external service like ident.me in order to discover the external IP address of your router.

Here is how it is done with python3, using nothing else but the standard library:

import urllib.request

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

print(external_ip)

Both IPv4 and IPv6 addresses can be returned, based on availability and client preference; use https://v4.ident.me/ for IPv4 only, or https://v6.ident.me/ for IPv6 only.

寄居者 2024-08-29 15:39:51

我更喜欢这个 Amazon AWS 端点:

import requests
ip = requests.get('https://checkip.amazonaws.com').text.strip()

I prefer this Amazon AWS endpoint:

import requests
ip = requests.get('https://checkip.amazonaws.com').text.strip()
海螺姑娘 2024-08-29 15:39:51

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

If you are behind a router which obtains the external IP, I'm afraid you have no other option but to use external service like you do. If the router itself has some query interface, you can use it, but the solution will be very environment-specific and unreliable.

梦屿孤独相伴 2024-08-29 15:39:51

您应该使用UPnP 协议来查询您的路由器以获取此信息。最重要的是,这不依赖于外部服务,这个问题的所有其他答案似乎都表明了这一点。

有一个名为 miniupnp 的 Python 库可以执行此操作,请参阅 miniupnpc/ testupnpigd.py

pip install miniupnpc

根据他们的示例,您应该能够执行以下操作:

import miniupnpc

u = miniupnpc.UPnP()
u.discoverdelay = 200
u.discover()
u.selectigd()
print('external ip address: {}'.format(u.externalipaddress()))

You should use the UPnP protocol to query your router for this information. Most importantly, this does not rely on an external service, which all the other answers to this question seem to suggest.

There's a Python library called miniupnp which can do this, see e.g. miniupnpc/testupnpigd.py.

pip install miniupnpc

Based on their example you should be able to do something like this:

import miniupnpc

u = miniupnpc.UPnP()
u.discoverdelay = 200
u.discover()
u.selectigd()
print('external ip address: {}'.format(u.externalipaddress()))
用心笑 2024-08-29 15:39:51

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

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

这样。

In my opinion the simplest solution is

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

Thats all.

(り薆情海 2024-08-29 15:39:51

使用请求模块:

import requests

myip = requests.get('https://www.wikipedia.org').headers['X-Client-IP']

print("\n[+] Public IP: "+myip)

Use requests module:

import requests

myip = requests.get('https://www.wikipedia.org').headers['X-Client-IP']

print("\n[+] Public IP: "+myip)
别挽留 2024-08-29 15:39:51

如果您不想使用外部服务(IP网站等),您可以使用UPnP协议。

为此,我们使用一个简单的 UPnP 客户端库 (https://github.com/flyte/upnpclient)

安装

pip 安装 upnpclient

简单代码

import upnpclient

devices = upnpclient.discover()

if(len(devices) > 0):
    externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
    print(externalIP)
else:
    print('No Connected network interface detected')

完整代码(以获取 github 自述文件中提到的更多信息)

In [1]: import upnpclient

In [2]: devices = upnpclient.discover()

In [3]: devices
Out[3]: 
[<Device 'OpenWRT router'>,
 <Device 'Harmony Hub'>,
 <Device 'walternate: root'>]

In [4]: d = devices[0]

In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]: 
{'NewConnectionStatus': 'Connected',
 'NewLastConnectionError': 'ERROR_NONE',
 'NewUptime': 14851479}

In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}

In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}

If you don't want to use external services (IP websites, etc.) You can use the UPnP Protocol.

Do to that we use a simple UPnP client library (https://github.com/flyte/upnpclient)

Install:

pip install upnpclient

Simple Code:

import upnpclient

devices = upnpclient.discover()

if(len(devices) > 0):
    externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
    print(externalIP)
else:
    print('No Connected network interface detected')

Full Code (to get more information as mentioned in the github readme)

In [1]: import upnpclient

In [2]: devices = upnpclient.discover()

In [3]: devices
Out[3]: 
[<Device 'OpenWRT router'>,
 <Device 'Harmony Hub'>,
 <Device 'walternate: root'>]

In [4]: d = devices[0]

In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]: 
{'NewConnectionStatus': 'Connected',
 'NewLastConnectionError': 'ERROR_NONE',
 'NewUptime': 14851479}

In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}

In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}
潦草背影 2024-08-29 15:39:51

就像在 Python3 中运行一样简单:

import os

externalIP  = os.popen('curl -s ifconfig.me').readline()
print(externalIP)

As simple as running this in Python3:

import os

externalIP  = os.popen('curl -s ifconfig.me').readline()
print(externalIP)
千纸鹤 2024-08-29 15:39:51

尝试:

import requests 
ip = requests.get('http://ipinfo.io/json').json()['ip']

希望这有帮助

Try:

import requests 
ip = requests.get('http://ipinfo.io/json').json()['ip']

Hope this is helpful

往事风中埋 2024-08-29 15:39:51

如果您认为外部来源太不可靠,您可以汇集一些不同的服务。对于大多数 ip 查找页面,他们要求您抓取 html,但其中一些页面已经为像您这样的脚本创建了精简页面 - 也因此他们可以减少其网站上的点击量:

If you think and external source is too unreliable, you could pool a few different services. For most ip lookup pages they require you to scrape html, but a few of them that have created lean pages for scripts like yours - also so they can reduce the hits on their sites:

稚气少女 2024-08-29 15:39:51

我使用 IPGrab 因为它很容易记住:

# 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('http://ipgrab.io').text
print('My public IP address is: {}'.format(ip))

I use IPGrab because it's easy to remember:

# 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('http://ipgrab.io').text
print('My public IP address is: {}'.format(ip))
心头的小情儿 2024-08-29 15:39:51

还有一些其他方法不依赖于 Python 检查外部网站,但操作系统可以。这里的主要问题是,即使您没有使用 Python,如果您使用的是命令行,也没有“内置”命令可以简单地告诉您外部 (WAN) IP。 “ip addr show”和“ifconfig -a”等命令会显示网络中服务器的 IP 地址。只有路由器真正拥有外部IP。但是,有多种方法可以从命令行查找外部 IP 地址 (WAN IP)。

这些示例是:

http://ipecho.net/plain ; echo
curl ipinfo.io/ip
dig +short myip.opendns.com @resolver1.opendns.com
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com

因此,python 代码将是:

import os
ip = os.popen('wget -qO- http://ipecho.net/plain ; echo').readlines(-1)[0].strip()
print ip

OR

import os
iN, out, err = os.popen3('curl ipinfo.io/ip')
iN.close() ; err.close()
ip = out.read().strip()
print ip

OR

import os
ip = os.popen('dig +short myip.opendns.com @resolver1.opendns.com').readlines(-1)[0].strip()
print ip

或者,将上面的任何其他示例插入到 os.popen、os.popen2、os.popen3 或 os.system 等命令中。

PS你可以使用“pip3 install pytis”并使用/看一下用Python编写的“getip”程序。
您还可以在这里找到它的代码:https://github。 com/PyTis/PyTis/blob/development/src/pytis/getip.py

There are a few other ways that do not rely on Python checking an external web site, however the OS can. Your primary issue here, is that even if you were not using Python, if you were using the command line, there are no "built-in" commands that can just simply tell you the external (WAN) IP. Commands such as "ip addr show" and "ifconfig -a" show you the server's IP address's within the network. Only the router actually holds the external IP. However, there are ways to find the external IP address (WAN IP) from the command line.

These examples are:

http://ipecho.net/plain ; echo
curl ipinfo.io/ip
dig +short myip.opendns.com @resolver1.opendns.com
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com

Therefore, the python code would be:

import os
ip = os.popen('wget -qO- http://ipecho.net/plain ; echo').readlines(-1)[0].strip()
print ip

OR

import os
iN, out, err = os.popen3('curl ipinfo.io/ip')
iN.close() ; err.close()
ip = out.read().strip()
print ip

OR

import os
ip = os.popen('dig +short myip.opendns.com @resolver1.opendns.com').readlines(-1)[0].strip()
print ip

Or, plug any other of the examples above, into a command like os.popen, os.popen2, os.popen3, or os.system.

P.S. you can use "pip3 install pytis" and use/take a look at, the "getip" program, written in Python.
You can also find it's code here: https://github.com/PyTis/PyTis/blob/development/src/pytis/getip.py

爱本泡沫多脆弱 2024-08-29 15:39:51

不幸的是,如果不咨询互联网上的计算机,就无法获取您的外部 IP 地址。最好的情况是,您可以获得网卡的本地网络 IP 地址(可能是 192.16.. 地址)。

您可以使用 whatismyip 模块获取外部 IP 地址。它没有 Python 3 标准库之外的依赖项。它连接到公共 STUN 服务器和 What-is-my-ip 网站以查找 IPv4 或 IPv6 地址。运行 pip install whatismyip

示例:

>>> import whatismyip
>>> whatismyip.amionline()
True
>>> whatismyip.whatismyip()  # Prefers IPv4 addresses, but can return either IPv4 or IPv6.
'69.89.31.226'
>>> whatismyip.whatismyipv4()
'69.89.31.226'
>>> whatismyip.whatismyipv6()
'2345:0425:2CA1:0000:0000:0567:5673:23b5'

Unfortunately, there is no way to get your external IP address without consulting a computer on the internet. At best, you can get the local network IP address of your network card (which is likely a 192.16.. address).

You can use the whatismyip module to get the external IP addres. It has no dependencies outside the Python 3 standard library. It connects to public STUN servers and what-is-my-ip websites to find the IPv4 or IPv6 address. Run pip install whatismyip

Example:

>>> import whatismyip
>>> whatismyip.amionline()
True
>>> whatismyip.whatismyip()  # Prefers IPv4 addresses, but can return either IPv4 or IPv6.
'69.89.31.226'
>>> whatismyip.whatismyipv4()
'69.89.31.226'
>>> whatismyip.whatismyipv6()
'2345:0425:2CA1:0000:0000:0567:5673:23b5'
行至春深 2024-08-29 15:39:51
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"
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"
鸠魁 2024-08-29 15:39:51

我能想到的最简单(非Python)工作解决方案是

wget -q -O- icanhazip.com

我想添加一个非常短的Python3解决方案,它利用 http://hostip.info

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

The most simple (non python) working solution I can think of is

wget -q -O- icanhazip.com

I'd like to add a very short Python3 solution which makes use of the JSON API of http://hostip.info.

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'])

You can of course add some error checking, a timeout condition and some convenience:

#!/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
亣腦蒛氧 2024-08-29 15:39:51

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

这是一个应该可以解决问题并仅下载最少量信息的脚本:

#!/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() )

I tried most of the other answers on this question here and came to find that most of the services used were defunct except one.

Here is a script that should do the trick and download only a minimal amount of information:

#!/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() )
帅气称霸 2024-08-29 15:39:51

使用Python 2.7.6和2.7.13

import urllib2  
req = urllib2.Request('http://icanhazip.com', data=None)  
response = urllib2.urlopen(req, timeout=5)  
print(response.read())

Working with Python 2.7.6 and 2.7.13

import urllib2  
req = urllib2.Request('http://icanhazip.com', data=None)  
response = urllib2.urlopen(req, timeout=5)  
print(response.read())
岛徒 2024-08-29 15:39:51

如果机器是防火墙,那么您的解决方案是一个非常明智的解决方案:另一种方法是能够查询防火墙,这最终非常依赖于防火墙的类型(如果可能的话)。

If the machine is being a firewall then your solution is a very sensible one: the alternative being able to query the firewall which ends-up being very dependent on the type of firewall (if at all possible).

晚雾 2024-08-29 15:39:51
In [1]: import stun

stun.get_ip_info()
('Restric NAT', 'xx.xx.xx.xx', 55320)
In [1]: import stun

stun.get_ip_info()
('Restric NAT', 'xx.xx.xx.xx', 55320)
苍景流年 2024-08-29 15:39:51

仅限 Linux 的解决方案。

在 Linux 系统上,您可以使用 Python 在 shell 上执行命令。我认为这可能对某人有帮助。

像这样的东西,(假设“dig/drill”正在操作系统上运行)

import os 
command = "dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | awk -F\'\"\' '{print $2}' " 
ip = os.system(command)

对于 Arch 用户,请将“dig”替换为“drill”。

Linux only solution.

On Linux Systems, you can use Python to execute a command on the shell. I think it might help someone.

Something like this, (assuming 'dig/drill' is working on the os)

import os 
command = "dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | awk -F\'\"\' '{print $2}' " 
ip = os.system(command)

For Arch users, please replace 'dig' with 'drill'.

薄荷港 2024-08-29 15:39:51

我喜欢 Sergiy Ostrovsky 的回答,但我认为现在有一种更简洁的方法可以做到这一点。

  1. 安装 ipify 库。
pip install ipify
  1. 在 Python 程序中导入并使用该库。
import ipify
ip = ipify.get_ip()

I liked Sergiy Ostrovsky's answer, but I think there is an even tidier way to do this now.

  1. Install ipify library.
pip install ipify
  1. Import and use the library in your Python program.
import ipify
ip = ipify.get_ip()
臻嫒无言 2024-08-29 15:39:51
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 就不那么痛苦了。

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]

this is a short snippet I had written for another program. The trick was finding a simple enough website so that dissecting the html wasn't a pain.

沧笙踏歌 2024-08-29 15:39:51

这是另一个替代脚本。

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

编辑:不要忘记导入 httplib 和 json

Here's another alternative script.

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

EDIT: Don't forget to import httplib and json

╰つ倒转 2024-08-29 15:39:51

如果您只是为自己编写而不是为通用应用程序编写,那么您也许可以在路由器的设置页面上找到地址,然后从该页面的 html 中抓取它。这对于我的 SMC 路由器来说效果很好。一读再简单的 RE 搜索,我就找到了它。

我对此特别感兴趣的是,当我离开家时,让我知道我的家庭 IP 地址,以便我可以通过 VNC 返回。再用几行 Python 代码将地址存储在 Dropbox 中以供外部访问,如果发现变化,甚至会向我发送电子邮件。我已安排它在启动时发生,此后每小时发生一次。

If you're just writing for yourself and not for a generalized application, you might be able to find the address on the setup page for your router and then scrape it from that page's html. This worked fine for me with my SMC router. One read and one simple RE search and I've found it.

My particular interest in doing this was to let me know my home IP address when I was away from home, so I could get back in via VNC. A few more lines of Python stores the address in Dropbox for outside access, and even emails me if it sees a change. I've scheduled it to happen on boot and once an hour thereafter.

暮年 2024-08-29 15:39:51

使用此脚本:

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

Use this script :

import urllib, json

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

Without json :

import urllib, re

data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1)
print data
江心雾 2024-08-29 15:39:51

导入操作系统
public_ip = os.system("inxi -i |grep 'WAN IP'")
打印(公共IP)

import os
public_ip = os.system("inxi -i |grep 'WAN IP'")
print(public_ip)

零崎曲识 2024-08-29 15:39:51

要获取外部 IP 地址,请使用以下代码:

from requests import get

def get_external_ip()->str:
    return get('https://api.ipify.org/').text

To get external IP address, use this code:

from requests import get

def get_external_ip()->str:
    return get('https://api.ipify.org/').text
阪姬 2024-08-29 15:39:51

如果您经常检查,亚马逊页面会阻止该请求。也许其他人也这样做。此代码为每次调用选择一个新链接,并且仅在有有效结果时才返回。如果响应确实包含 IP 地址,也许也是个好主意。因此,我使用了这里的正则表达式: https://stackoverflow.com/a/36760050

import re
import random
import requests

ipreg = re.compile(
    r"""^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$"""
)


def _getip(link, action):
    result = None
    try:
        with requests.get(link) as fa:
            result = action(fa)
            result = ipreg.findall(result)[0]
    except Exception:
        pass
    return result


def get_ip_of_this_pc():
    fu1 = lambda fa: fa.text.strip()
    fu2 = lambda fa: fa.json()["ip"].strip()
    sites_and_actions = [
        ("https://checkip.amazonaws.com", fu1),
        ("https://api.ipify.org", fu1),
        ("https://ident.me", fu1),
        ("http://myip.dnsomatic.com", fu1),
        ("http://ipinfo.io/json", fu2),
        ("http://ipgrab.io", fu1),
        ("http://icanhazip.com/", fu1),
        ("https://www.trackip.net/ip", fu1),
    ]
    random.shuffle(sites_and_actions)
    for link, action in sites_and_actions:
        result = _getip(link, action)
        if result:
            return result


myip = get_ip_of_this_pc()
print(myip)

If you are checking frequently, the amazon page blocks the request. Maybe others do so too. This code chooses each call a new link, and only returns if there is a valid result. Maybe it is also a good idea if the response really contains an IP address. Because of that, I used the regex from here: https://stackoverflow.com/a/36760050

import re
import random
import requests

ipreg = re.compile(
    r"""^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])
quot;""
)


def _getip(link, action):
    result = None
    try:
        with requests.get(link) as fa:
            result = action(fa)
            result = ipreg.findall(result)[0]
    except Exception:
        pass
    return result


def get_ip_of_this_pc():
    fu1 = lambda fa: fa.text.strip()
    fu2 = lambda fa: fa.json()["ip"].strip()
    sites_and_actions = [
        ("https://checkip.amazonaws.com", fu1),
        ("https://api.ipify.org", fu1),
        ("https://ident.me", fu1),
        ("http://myip.dnsomatic.com", fu1),
        ("http://ipinfo.io/json", fu2),
        ("http://ipgrab.io", fu1),
        ("http://icanhazip.com/", fu1),
        ("https://www.trackip.net/ip", fu1),
    ]
    random.shuffle(sites_and_actions)
    for link, action in sites_and_actions:
        result = _getip(link, action)
        if result:
            return result


myip = get_ip_of_this_pc()
print(myip)
柠北森屋 2024-08-29 15:39:51

上述答案要么过时,要么复杂。目前,这适用于最新的 python 3.11=

import urllib.request
import json

def get_external_ip():
    try:
        response = urllib.request.urlopen("https://httpbin.org/ip")
        data = json.load(response)
        address = data['origin']
        return address
    except Exception as e:
        return str(e)

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

Above answers are either outdated or intricate. This works currently on latest python 3.11=

import urllib.request
import json

def get_external_ip():
    try:
        response = urllib.request.urlopen("https://httpbin.org/ip")
        data = json.load(response)
        address = data['origin']
        return address
    except Exception as e:
        return str(e)

if __name__ == '__main__':
    print(get_external_ip())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文