Shell方式

python -c "import socket;print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])"

在程序脚本中使用

import socket

def get_host_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()

    return ip

原文地址:https://www.chenyudong.com/archives/python-get-local-ip-graceful.html

[ 编辑 | 历史 ]
最近由“jilili”在“2018-03-25 23:32:26”修改