套接字 IO returns 127.0.0.1 作为主机地址而不是 192.168.0.* 在我的设备上

Socket IO returns 127.0.0.1 as host address and not 192.168.0.* on my device

当我 运行 以下代码确定我设备的本地 IP 地址时,我得到 127.0.0.1 而不是 192.168.0.101。

import socket
import threading

PORT = 8080
HOST_NAME = socket.gethostname()
print(HOST_NAME)
SERVER = socket.gethostbyname(HOST_NAME)

print(SERVER)

我在控制台上得到的输出是

MyDeviceName.local
127.0.0.1

试试这个:

NOTE - Tested on CentOS 7.9 using Python 3.6.8, and Ubuntu 20.04 using Python 3.8.10

NOTE - You may have to install psutil when using Ubuntu 20.04

import socket

import psutil

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
my_eip = s.getsockname()[0]
nics = psutil.net_if_addrs()
my_enic = [i for i in nics for j in nics[i]
           if j.address == my_eip and j.family == socket.AF_INET][0]
print('My Ethernet NIC name is {0} and my IPv4 address is {1}.'.format(
    my_enic, my_eip))

输出:

My Ethernet NIC name is enp0s3 and my IPv4 address is 192.168.0.101.

127.0.0.1是localhost地址,没错。如果您想要设备的地址,请执行以下操作:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])