以下是一个函数,可以同时返回:
- 本地内网 IP(非回环地址,如
192.168.x.x
,不依赖远程连接) - 远程出口 IP(默认网卡连接外网时系统使用的 IP)
✅ 完整代码如下:
import socket
import psutil
def get_local_ips_by_interface_and_remote():
local_ips_by_interface = {}
# 获取所有网卡及其非回环 IPv4 地址
for iface_name, iface_addrs in psutil.net_if_addrs().items():
ip_list = []
for addr in iface_addrs:
if addr.family == socket.AF_INET and not addr.address.startswith("127."):
ip_list.append(addr.address)
if ip_list:
local_ips_by_interface[iface_name] = ip_list
# 获取远程出口 IP
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
remote_ip = s.getsockname()[0]
s.close()
except Exception:
remote_ip = None
return (local_ips_by_interface, remote_ip)
# 示例输出
local_info, remote = get_local_ips_by_interface_and_remote()
print("本地 IP:", local_info)
print("远程出口 IP:", remote)
#本地 IP: {'eth0': ['192.168.1.100'], 'docker0': ['172.17.0.1']}
#远程出口 IP: 192.168.1.100
示例输出:
#本地 IP: {'eth0': ['192.168.1.100'], 'docker0': ['172.17.0.1']}
#远程出口 IP: 192.168.1.100
在大多数情况下,本地 IP 和远程 IP 是一样的,但如果你启用了 VPN、容器、虚拟机等,它们可能不同。