獲取本機主機名稱是網路診斷、日誌標識、分散式鎖等場景的基礎操作。本文提供最簡潔實作並延伸實際應用模式。
import socket
hostname = socket.gethostname()
print("Host name:", hostname)
import socket, uuid
machine_id = socket.gethostname() + '-' + str(uuid.getnode())
import logging, socket
hostname = socket.gethostname()
logging.basicConfig(
format='%(asctime)s [' + hostname + '] %(levelname)s: %(message)s',
level=logging.INFO
)
import socket
hostname = socket.gethostname()
if hostname.startswith('dev-'):
DEBUG = True
DB_HOST = 'dev-db'
elif hostname.startswith('prod-'):
DEBUG = False
DB_HOST = 'prod-db'
else:
DEBUG = True
DB_HOST = 'localhost'
import socket, os
def get_host_hostname():
# Docker: 讀取 /etc/hostname 或環境變數
if os.path.exists('/etc/hostname'):
with open('/etc/hostname') as f:
return f.read().strip()
return socket.gethostname()
| 問題 | 原因 | 解決 |
|---|---|---|
| 回傳 localhost | /etc/hosts 設定問題 | 檢查 hostname 指令與 /etc/hostname |
| 容器中顯示容器 ID | 容器獨立 UTS namespace | 掛載宿主 /etc/hostname 或用環境變數傳遞 |
| Windows 含特殊字元 | NetBIOS 名稱限制 | 僅作為標識使用,避免作為 DNS 名稱 |