Skip to content

Instantly share code, notes, and snippets.

@jkirklan
Created January 6, 2020 18:25
Show Gist options
  • Save jkirklan/cefe1ea2d10ba4c35d91eff9d986d959 to your computer and use it in GitHub Desktop.
Save jkirklan/cefe1ea2d10ba4c35d91eff9d986d959 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import sys
import socket
import fcntl
import struct
import array
def all_interfaces():
is_64bits = sys.maxsize > 2**32
struct_size = 40 if is_64bits else 32
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
max_possible = 8 # initial value
while True:
bytes = max_possible * struct_size
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]
if outbytes == bytes:
max_possible *= 2
else:
break
namestr = names.tostring()
return [(namestr[i:i+16].split('\0', 1)[0],
socket.inet_ntoa(namestr[i+20:i+24]))
for i in range(0, outbytes, struct_size)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment