核心 API 速查
| 方法 | 返回值 | 說明 |
socket.gethostname() | str | 本機主機名 (可能非 FQDN) |
socket.getfqdn([name]) | str | 完全限定域名 (FQDN) |
socket.gethostbyname(hostname) | str | IPv4 地址 (單個) |
socket.gethostbyname_ex(hostname) | tuple | (hostname, aliaslist, ipaddrlist) |
socket.getaddrinfo(host, port) | list | 完整地址信息 (IPv4/IPv6) |
方法一:基礎 hostname + gethostbyname
import socket
hostname = socket.gethostname()
print(f"Hostname: {hostname}") # 如: china-43226208c
ip = socket.gethostbyname(hostname)
print(f"Primary IPv4: {ip}") # 如: 192.168.3.196
# 獲取所有 IPv4
try:
_, _, ips = socket.gethostbyname_ex(hostname)
print(f"All IPv4: {ips}") # ['192.168.3.196', '10.0.0.1', ...]
except socket.gaierror:
print("Resolution failed")
方法二:getfqdn 獲取標準主機名
fqdn = socket.getfqdn(socket.gethostname())
print(f"FQDN: {fqdn}") # 如: china-43226208c.localdomain
方法三:getaddrinfo 完整解析 (支援 IPv6)
def get_all_ips(hostname=None):
"""獲取所有網卡 IP (IPv4 + IPv6)"""
if hostname is None:
hostname = socket.gethostname()
infos = socket.getaddrinfo(hostname, None) # port=None 表示不解析端口
ips = set()
for family, type_, proto, canonname, sockaddr in infos:
ip = sockaddr[0]
# 過濾回環、鏈路本地等
if not ip.startswith(('127.', '::1', 'fe80::')):
ips.add(ip)
return list(ips)
print(get_all_ips())
# ['192.168.3.196', '2001:db8::1', '10.0.0.5']
方法四:遍歷網卡接口 (psutil 推薦)
# pip install psutil
import psutil
def get_interface_ips():
"""按網卡接口獲取 IP,含掩碼、廣播地址"""
addrs = psutil.net_if_addrs()
result = {}
for iface, addr_list in addrs.items():
result[iface] = []
for addr in addr_list:
if addr.family in (socket.AF_INET, socket.AF_INET6):
result[iface].append({
'ip': addr.address,
'netmask': addr.netmask,
'broadcast': addr.broadcast,
'family': 'IPv4' if addr.family == socket.AF_INET else 'IPv6'
})
return result
# 輸出示例
# {
# 'Ethernet0': [{'ip': '192.168.3.196', 'netmask': '255.255.255.0', 'family': 'IPv4'}],
# 'Wi-Fi': [{'ip': '10.0.0.5', 'netmask': '255.255.255.0', 'family': 'IPv4'}],
# 'lo': [{'ip': '127.0.0.1', 'netmask': '255.0.0.0', 'family': 'IPv4'}]
# }
獲取公網 IP (需外部服務)
import urllib.request
import json
def get_public_ip():
services = [
'https://api.ipify.org?format=json',
'https://httpbin.org/ip',
'https://ipinfo.io/json'
]
for url in services:
try:
with urllib.request.urlopen(url, timeout=5) as resp:
data = json.load(resp)
return data.get('ip') or data.get('origin', '').split(',')[0].strip()
except:
continue
return None
print(f"Public IP: {get_public_ip()}")
常見陷阱與解決
| 現象 | 原因 | 解決 |
| 返回 127.0.0.1 | /etc/hosts 將 hostname 映射到回環 | 檢查 /etc/hosts,優先使用 getaddrinfo 或 psutil |
| 多網卡只返回一個 IP | gethostbyname 僅返回第一條 A 記錄 | 使用 gethostbyname_ex 或 psutil 遍歷接口 |
| 容器內獲取宿主機 IP | 容器網絡命名空間隔離 | 讀取 /etc/hosts 或環境變量,或宿主機網絡模式 |
| IPv6 連通性測試 | 需雙棧環境 | 使用 socket.AF_INET6 測試連接 |
最佳實踐封裝
import socket
import psutil
from typing import List, Dict
class NetworkInfo:
@staticmethod
def get_hostname() -> str:
return socket.gethostname()
@staticmethod
def get_fqdn() -> str:
return socket.getfqdn()
@staticmethod
def get_local_ips() -> List[str]:
"""獲取所有非回環 IPv4/IPv6"""
ips = set()
for addrs in psutil.net_if_addrs().values():
for addr in addrs:
if addr.family in (socket.AF_INET, socket.AF_INET6):
ip = addr.address
if not ip.startswith(('127.', '::1', 'fe80::', '169.254.')):
ips.add(ip)
return list(ips)
@staticmethod
def get_interfaces() -> Dict[str, List[Dict]]:
"""按接口獲取詳細信息"""
result = {}
for iface, addrs in psutil.net_if_addrs().items():
result[iface] = [{
'ip': a.address, 'netmask': a.netmask,
'broadcast': a.broadcast, 'family': 'IPv4' if a.family == socket.AF_INET else 'IPv6'
} for a in addrs if a.family in (socket.AF_INET, socket.AF_INET6)]
return result
@staticmethod
def get_public_ip() -> str:
# 同前文實現
pass
根據場景選擇:簡單腳本用 socket 標準庫;運維工具、監控系統強烈推薦 psutil,功能全、跨平台、無外部依賴。