Skip to content

Instantly share code, notes, and snippets.

@sphaero
Created January 2, 2014 10:31
Show Gist options
  • Save sphaero/8217404 to your computer and use it in GitHub Desktop.
Save sphaero/8217404 to your computer and use it in GitHub Desktop.
Get all interfaces and ipaddressen, python3 compatible. Tested on Linux
# Compatible with Python3, tested on Linux
# Author Arnaud Loonstra <arnaud@sphaero.org>
# based on <http://code.activestate.com/recipes/439093/#c1>
import socket
import fcntl
import struct
import array
import sys
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(b'\x00', 1)[0]
ip = namestr[i+20:i+24]
lst.append((name, ip))
return lst
def format_ip(addr):
# check python version
if sys.version_info.major > 2:
return "%i.%i.%i.%i" %(addr[0], addr[1], addr[2], addr[3])
return "%s.%s.%s.%s" %(addr[0], addr[1], addr[2], addr[3])
ifs = all_interfaces()
for i in ifs:
print("%12s %s" % (i[0].decode('utf-8'), format_ip(i[1])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment