-
Notifications
You must be signed in to change notification settings - Fork 2
/
netstats.py
51 lines (38 loc) · 1.36 KB
/
netstats.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2013, Rui Carmo
Description: Network utility functions
License: MIT (see LICENSE.md for details)
"""
import re
import logging
import socket
import struct
log = logging.getLogger()
def valid_mac_address(addr):
"""Validate a physical Ethernet address"""
return re.match("[0-9a-f]{2}([-:][0-9a-f]{2}){5}$", addr.lower())
def valid_ip_address(addr):
"""Quick and dirty way to validate any kind of IP address"""
try:
socket.inet_aton(addr)
return True
except socket.error:
return False
def get_net_bytes(dev='eth0'):
"""Read network interface traffic counters"""
return {
'rx': float(open('/sys/class/net/%s/statistics/rx_bytes' % dev,'r').read().strip()),
'tx': float(open('/sys/class/net/%s/statistics/tx_bytes' % dev,'r').read().strip())
}
def get_mac_address(dev="eth0"):
"""Retrieves the MAC address from the /sys virtual filesystem - will only work on Linux."""
return open('/sys/class/net/%s/address' % dev,'r').read().strip()
def get_ip_address(dev="eth0"):
"""Retrieves the IP address via SIOCGIFADDR - only tested on Linux."""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', dev[:15]))[20:24])
except:
return None