Python获取本机IP

2024-01-10 16:13:07

以下代码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

文章来源:https://blog.csdn.net/jaket5219999/article/details/135504498
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。