Python获取hostname的方法

概述

目前共找到4种方法,均已实测有效。 综合考虑可靠性与跨平台,建议使用platform模块与Socket.gethostname()

  1. os模块

不支持Windows平台,Linux亲测可用 windows平台下使用将会报错: AttributeError: module 'os' has no attribute 'uname'.

import os,platform
info = os.uname()
hostname = info.nodename

  1. platform模块 支持跨平台,亲测Windows与Linux下可用。
    import platform
    hostname = platform.node()
    1. Socket模块

3.1 Socket.gethostname()

通过Socket.gethostname()直接获取 支持跨平台,亲测Windows与Linux下可用。

import socket
hostname = socket.gethostname()

3.2 Socket.gethostbyaddr()

通过IP地址获取,在某些场景下适用,如已知本机或远程主机的ip,需获取hostname 支持跨平台,亲测Windows与Linux下可用。

但此方法不可靠,在某些场景下会报错:socket.herror: [Errno 11004] host not found

import socket
hostname = socket.gethostbyaddr("8.8.8.8")[0]