You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.3 KiB

This borrows extensivelly from Gnome Network Monitor
Gnome-network-monitor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2 of the License.
import socket
import fcntl
SIOCGIFHWADDR = 0x8927 # MAC address
SIOCGIFADDR = 0x8915 # IPv4 address
SIOCGIFNETMASK = 0x891B # interface mask
SIOCGIFBRDADDR = 0x8919 # broadcast address
#def get_interfaces():
#Returns a list of all network interfaces present, such as [eth0, eth1, lo]
fl = open('/proc/net/dev','r')
lines = fl.readlines()
print [ l[:l.find(":")].strip() for l in lines if ":" in l ]
# end def get_interfaces():
#def get_iface_statistics(iface):
keys_dyn_data = ["bytes_in", "packets_in","errors_in", "bytes_out", "packets_out","errors_out" ]
a = 'eth0'
delim = "%s:" % (a) # "eth0:"
if_numbers = [ t.strip().strip(delim) for t in lines if delim in t ][0]
iface_data = dict(zip(keys_dyn_data, [ int(if_numbers.split()[index]) for index in (0, 1, 2, 8, 9, 10)]))
print iface_data
#end def get_iface_statistics
#helper for get_MAC_address
def strip_hex(n):
return "%02x" % (ord(n))
# end helper for get_MAC_address
#def get_MAC_address(self, iface):
Returns the MAC address for an interface or None if the
interface does not have one.
iface = 'eth0'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
iface = iface.strip()
ifr = iface + '\0'*(32-len(iface))
r = fcntl.ioctl(s.fileno(), SIOCGIFADDR, ifr)
addr = map(strip_hex, r[18:24])
ret = (':'.join(map(str, addr)))
except IOError:
ret = ''
print ret
# end def get_MAC_address(self, iface):
#helper for iface data except MAC
#def __get_socket_data(self, iface, ioctl_const):
def get_socket_data(iface, ioctl_const):
#Calls ioctl with a given constant.
sockfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ifreq = (iface + '\0'*32)[:32]
result = fcntl.ioctl(sockfd.fileno(), ioctl_const, ifreq)
return socket.inet_ntoa(result[20:24])
except IOError:
return "None"
# end helper for iface data except MAC
print get_socket_data('eth0', SIOCGIFADDR)
print get_socket_data('eth0', SIOCGIFNETMASK)
print get_socket_data('eth0', SIOCGIFBRDADDR)