python-공개 IP를위한 발신 대역폭

Aug 19 2020

아래 코드 줄을 사용하여 centos 상자에서 보낸 총 바이트를 확인하고 있습니다.

import psutil
psutil.net_io_counters().bytes_sent

퍼블릭 IP에 대해서만 수행하고 싶습니다. 즉, 퍼블릭 IP에 대해서만 나가는 대역폭을 계산하고 싶습니다.

답변

kerasbaz Aug 20 2020 at 03:11
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