Return all interfaces that are up
()
| 85 | |
| 86 | # from: https://code.activestate.com/recipes/439093/ |
| 87 | def all_interfaces(): |
| 88 | ''' |
| 89 | Return all interfaces that are up |
| 90 | ''' |
| 91 | import fcntl # Linux only, so only import when required |
| 92 | |
| 93 | is_64bits = sys.maxsize > 2**32 |
| 94 | struct_size = 40 if is_64bits else 32 |
| 95 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 96 | max_possible = 8 # initial value |
| 97 | while True: |
| 98 | bytes = max_possible * struct_size |
| 99 | names = array.array('B', b'\0' * bytes) |
| 100 | outbytes = struct.unpack('iL', fcntl.ioctl( |
| 101 | s.fileno(), |
| 102 | 0x8912, # SIOCGIFCONF |
| 103 | struct.pack('iL', bytes, names.buffer_info()[0]) |
| 104 | ))[0] |
| 105 | if outbytes == bytes: |
| 106 | max_possible *= 2 |
| 107 | else: |
| 108 | break |
| 109 | namestr = names.tobytes() |
| 110 | return [(namestr[i:i+16].split(b'\0', 1)[0], |
| 111 | socket.inet_ntoa(namestr[i+20:i+24])) |
| 112 | for i in range(0, outbytes, struct_size)] |
| 113 | |
| 114 | def addr_to_hex(addr): |
| 115 | ''' |