Skip to content

Instantly share code, notes, and snippets.

@rushiagr
Forked from pklaus/enumerate_interfaces.py
Last active December 31, 2015 04:19
Show Gist options
  • Save rushiagr/7932978 to your computer and use it in GitHub Desktop.
Save rushiagr/7932978 to your computer and use it in GitHub Desktop.
Python version info
# Use those functions to enumerate all interfaces available on the system using Python.
# found on <http://code.activestate.com/recipes/439093/#c1>
# Works with Python 2.7
# Python 3.3's 'socket' module takes care of many of the functionalities coded here
import socket
import fcntl
import struct
import array
def all_interfaces():
max_possible = 128 # arbitrary. raise if needed.
bytes = max_possible * 32
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array('B', '\0' * bytes)
outbytes = struct.unpack('iL', fcntl.ioctl(
s.fileno(),
0x8912, # SIOCGIFCONF
struct.pack('iL', bytes, names.buffer_info()[0])
))[0]
namestr = names.tostring()
lst = []
for i in range(0, outbytes, 40):
name = namestr[i:i+16].split('\0', 1)[0]
ip = namestr[i+20:i+24]
lst.append((name, ip))
return lst
def format_ip(addr):
return str(ord(addr[0])) + '.' + \
str(ord(addr[1])) + '.' + \
str(ord(addr[2])) + '.' + \
str(ord(addr[3]))
ifs = all_interfaces()
for i in ifs:
print "%12s %s" % (i[0], format_ip(i[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment