获取本地ip

import socket
_local_ip = None


def get_host_ip():
    global _local_ip
    s = None
    try:
        if not _local_ip:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            _local_ip = s.getsockname()[0]
        return _local_ip
    finally:
        if s:
            s.close()
posted @ 2023-01-10 16:36  公众号海哥python  阅读(30)  评论(0编辑  收藏  举报