问题描述
我正在使用下面的代码行来检查从centos框中发送的总字节数
import psutil
psutil.net_io_counters().bytes_sent
我只想对公共IP执行此操作。换句话说,我只想计算公共IP的传出带宽。
解决方法
import ipaddress
import psutil
net = psutil.net_io_counters(pernic=True)
for name,interface in psutil.net_if_addrs().items():
for address in interface:
try:
network = ipaddress.IPv4Network(f'{address.address}\{address.netmask}')
if not network.is_private and not network.is_reserved:
print(net[name].bytes_sent)
break
except ValueError as e:
# these would be eg MAC addresses or similar
pass