如何找到本地IP地址(即192.168.x。x或10.0.x.x)在Python平台独立,只使用标准库?


当前回答

127.0.1.1是您的真实IP地址。更一般地说,一台计算机可以有任意数量的IP地址。您可以过滤它们为私有网络- 127.0.0.0/8,10.0.0.0/8,172.16.0.0/12和192.168.0.0/16。

但是,没有跨平台的方法来获取所有的IP地址。在Linux上,可以使用SIOCGIFCONF ioctl。

其他回答

另一个变体的前面的答案,可以保存到一个名为my-ip-to的可执行脚本:

#!/usr/bin/env python

import sys, socket

if len(sys.argv) > 1:
    for remote_host in sys.argv[1:]:
        # determine local host ip by outgoing test to another host
        # use port 9 (discard protocol - RFC 863) over UDP4
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.connect((remote_host, 9))
            my_ip = s.getsockname()[0]
            print(my_ip, flush=True)
else:
    import platform

    my_name = platform.node()
    my_ip = socket.gethostbyname(my_name)
    print(my_ip)

它需要任意数量的远程主机,并打印出本地ip,逐个到达它们:

$ my-ip-to z.cn g.cn localhost
192.168.11.102
192.168.11.102
127.0.0.1
$

并在没有给出arg时打印best-bet。

$ my-ip-to
192.168.11.102

如果计算机有到Internet的路由,即使/etc/hosts没有正确设置,这也将始终工作以获得首选的本地ip地址。

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 1))  # connect() for UDP doesn't send packets
local_ip_address = s.getsockname()[0]

Windows解决方案,要么接受,要么放弃。

在当前活动的无线局域网[无线局域网]上,即计算机的ip地址(wifi路由器或网络交换机)。

注意:它不是设备的公共IP,不涉及任何外部请求、包和公共api。

核心思想是解析shell命令:ipconfig或linux上的ifconfig的输出。我们使用子进程来获取输出。

def wlan_ip():
    import subprocess
    result=subprocess.run('ipconfig',stdout=subprocess.PIPE,text=True).stdout.lower()
    scan=0
    for i in result.split('\n'):
        if 'wireless' in i: #use "wireless" or wireless adapters and "ethernet" for wired connections
            scan=1
        if scan:
            if 'ipv4' in i:
                return i.split(':')[1].strip()
print(wlan_ip())

这是在CMD:'ipconfig'后发生的事情:

我们得到这个输出,我们在python中使用subprocess output捕获它。

C:\Users\戴尔> ipconfig

Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::f485:4a6a:e7d5:1b1c%4
   IPv4 Address. . . . . . . . . . . : 192.168.0.131
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.0.1

我们用python语言解析了字符串,以选择当前网络上无线适配器的IP的方式。

一台计算机可以有多个网络接口(包括您提到的本地环回127.0.0.1)。就操作系统而言,它也是一个“真实IP地址”。

如果你想跟踪所有的接口,看看下面的Python包,参见:http://alastairs-place.net/netifaces/

我认为,如果您从主机文件中删除环回条目,就可以避免gethostbyname返回127.0.0.1。(有待核实)。

简单而甜蜜!

def getip():

    import socket
    hostname= socket.gethostname()
    ip=socket.gethostbyname(hostname)

    return(ip)