Python - 获取localhost IP

时间:2012-07-31 08:13:05

标签: python sockets ip-address

  

可能重复:
  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)来修改配置文件。我怎么能得到它?

2 个答案:

答案 0 :(得分:25)

我通常使用此代码:

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。

修改

usedsmerlin stackoverflow问题中,此代码为this

答案 1 :(得分:17)

您可以使用一个漂亮的模块。它叫做netifaces。只需将一个pip安装netifaces放入virtualenv进行测试,然后尝试以下代码:

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://enabledns.com/ip')
print ret.read()

希望这有帮助。