psutil
是一个 Python 库,用于获取系统使用情况,如 CPU、内存、磁盘和网络接口等
import psutil
net_interfaces = psutil.net_if_addrs()
for interface, addrs in net_interfaces.items():
print(f"Interface: {interface}")
for addr in addrs:
print(f" Address: {addr.address}, Mask: {addr.netmask}, Broadcast: {addr.broadcast}")
import psutil
connections = psutil.net_connections()
for conn in connections:
print(f"Protocol: {conn.info['type']}, Local Address: {conn.laddr}, Remote Address: {conn.raddr}")
import psutil
net_io_counters = psutil.net_io_counters()
print(f"Bytes Sent: {net_io_counters.bytes_sent}")
print(f"Bytes Received: {net_io_counters.bytes_recv}")
import psutil
tcp_connections = psutil.net_tcp_stats()
udp_connections = psutil.net_udp_stats()
print("TCP Connections:")
for conn, stats in tcp_connections.items():
print(f" State: {stats.status}, Recv Queue: {stats.recv_queue}, Send Queue: {stats.send_queue}")
print("\nUDP Connections:")
for conn, stats in udp_connections.items():
print(f" Recv Queue: {stats.recv_queue}, Send Queue: {stats.send_queue}")
这些示例展示了如何使用 psutil
库来获取网络编程相关的信息。你可以根据自己的需求对这些示例进行修改和扩展。