【问题标题】:Python - Get localhost IP [duplicate]Python - 获取本地主机 IP [重复]
【发布时间】:2012-07-28 23:11:35
【问题描述】:

可能重复:
Finding local IP addresses using Python's stdlib

要获取我的本地主机 IP 地址,我会使用 socket.gethostbyname(socket.gethostname())。但它给了我答案127.0.0.1。 如果我这样做an_existing_socket.getsockname()[0],我会得到答案0.0.0.0

我需要我的“真实”IP 地址(例如 192.168.x.x)来修改配置文件。我怎么能得到它?

【问题讨论】:

  • @BigYellowCactus 你说得对,我会看看这些答案
  • @Germann Arlington 此配置文件注定要在另一台主机上使用:1)。我用我的 IP 和 2) 更新了 conf 文件。我远程启动 一个使用此 conf 文件的应用程序。由于多种原因,启动应用程序时我无法控制远程主机。
  • @Vaïk Godard - 在这种情况下,最好的解决方案是通过名称对其进行寻址,然后让网络 DNS 将其解析为该地址。
  • 当前的重复链接指向一个稍微不同的问题,该问题添加了“使用 Python 的标准库”。如果您可以忍受外部包,How do I determine all of my IP addresses when I have multiple NICs? 可能会更有帮助。

标签: python sockets ip-address


【解决方案1】:

我一般用这个代码:

import os
import socket

if os.name != "nt":
    import fcntl
    import struct

    def get_interface_ip(ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
                                ifname[:15]))[20:24])

def get_lan_ip():
    ip = socket.gethostbyname(socket.gethostname())
    if ip.startswith("127.") and os.name != "nt":
        interfaces = [
            "eth0",
            "eth1",
            "eth2",
            "wlan0",
            "wlan1",
            "wifi0",
            "ath0",
            "ath1",
            "ppp0",
            ]
        for ifname in interfaces:
            try:
                ip = get_interface_ip(ifname)
                break
            except IOError:
                pass
    return ip

我不知道它的来源,但它适用于 Linux/Windows。

编辑:

此代码是 used smerlinthis stackoverflow 问题中提出的。

【讨论】:

【解决方案2】:

您可以使用一个漂亮的模块。它被称为netifaces。只需在 virtualenv 中执行 pip install netifaces 进行测试,然后尝试以下代码:

import netifaces

interfaces = netifaces.interfaces()
for i in interfaces:
    if i == 'lo':
        continue
    iface = netifaces.ifaddresses(i).get(netifaces.AF_INET)
    if iface != None:
        for j in iface:
            print j['addr']

这完全取决于您的环境。如果你只有一个接口和一个 IP 地址,你可以这样做:

netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']

如果您在 NAT 之后并且想知道您的公共 IP 地址,您可以使用类似的方法:

import urllib2

ret = urllib2.urlopen('https://icanhazip.com/')
print ret.read()

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2014-06-01
    • 1970-01-01
    • 2014-10-24
    • 2018-09-06
    • 2012-04-12
    • 2017-02-02
    • 2013-10-28
    • 2017-10-31
    • 2018-07-14
    相关资源
    最近更新 更多