【问题标题】:How to get global ip address in python?如何在python中获取全局IP地址?
【发布时间】:2017-08-28 15:28:31
【问题描述】:

我正在将 bash 代码转换为 python 代码。 我通过 bash 代码获得了自己主机的全局 IP 地址

hostname -I  # output -> 19x.xxx.xxx.xxx xxxx:xxxx:....

19x.xxx.xxx.xxx是自己主机的全局ip地址。

我尝试通过

获取python中的全局ip地址
import socket
name=socket.gethostname()
id_address=socket.gethostbyname(name)
print("id_address = {0}".format(id_address))

输出是本地主机地址

127.xxx.xxx.xxx

我有办法在 python 中获取全局 IP 地址吗?

【问题讨论】:

  • 这是一个有趣的 -I 主机名标志,它似乎在 BSD 或 OS X 上不可用,你能告诉我你正在使用哪个程序吗?如果是这样,我们也许能够确定您需要在 python 中做什么。另外,如有必要,您可以在 python 中调用 shell 命令
  • @jmercouris:感谢您的评论。我正在使用 4.4.0-22-generic #39-Ubuntu。我可以在 bash shell 终端调用“hostname -I”。这是你想要的答案吗?恐怕我无法得到你真正想要的,因为我不是这个领域的专家。
  • 这可能会有所帮助:stackoverflow.com/a/30990617/6394138
  • 手册页中的-I 标志:显示主机的所有网络地址。此选项枚举所有网络接口上的所有配置地址。环回接口和 IPv6 链路本地地址被省略。与选项 -i 不同,此选项不依赖于名称解析。不要对输出的顺序做任何假设。
  • 记住“全球 ip”是一个主观术语,可能是重复的? How can I get the IP address of eth0 in Python?

标签: python


【解决方案1】:

无需任何外部库即可:

import urllib.request

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

print(external_ip)

这使用了一个网站,该网站仅使用标准库为您提供公共 ipv4 地址,这很棒。

代码在 python3 上测试。

类似问题:Getting a machine's external IP address with Python

类似答案:https://stackoverflow.com/a/41432835/14154066

【讨论】:

  • 请注意,这将返回您的“首选”IP 地址,无论是 IPv4 还是 IPv6。您必须仅将 v4.ident.me 用于 IPv4;更多详情@api.ident.me
【解决方案2】:

您必须使用互联网上的计算机/服务器将这些信息提供给您。你自己的电脑只能给你网卡在本地网络上的IP地址,e.g.类似于 192.16.8..

您可以使用 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'

【讨论】:

    猜你喜欢
    • 2014-07-23
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 2011-06-05
    • 2010-12-26
    • 2016-02-26
    相关资源
    最近更新 更多