以下代码Python3.11.6、MacOS系统中测试通过
import socket
def get_ip() -> str:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.settimeout(0)
try:
# doesn't even have to be reachable
s.connect(('10.254.254.254', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
return IP
print(get_ip())
Ref:networking - Finding local IP addresses using Python's stdlib - Stack Overflow
2024.08.30 补充:pip install -U asynctor 然后 from asynctor.utils import get_machine_ip即可