Advertisement
rfmonk

net_iface.py

Jun 26th, 2014
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # show network interfaces
  3. # like ifconfig
  4. # this is for a linux box
  5.  
  6.  
  7. import sys
  8. import socket
  9. import fcntl
  10. import struct
  11. import array
  12.  
  13. SIOCGIFCONF = 0x8912    # from C library sockios.h
  14. STRUCT_SIZE_32 = 32
  15. STRUCT_SIZE_64 = 40
  16. PLATFORM_32_MAX_NUMBER = 2**32
  17. DEFAULT_INTERFACES = 8
  18.  
  19.  
  20. def list_interfaces():
  21.     interfaces = []
  22.     max_interfaces = DEFAULT_INTERFACES
  23.     is_64bits = sys.maxsize > PLATFORM_32_MAX_NUMBER
  24.     struct_size = STRUCT_SIZE_64 if is_64bits else STRUCT_SIZE_32
  25.     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  26.     while True:
  27.         bytes = max_interfaces * struct_size
  28.         interface_names = array.array('B', '\0' * bytes)
  29.         sock_info = fcntl.ioctl(
  30.             sock.fileno(),
  31.             SIOCGIFCONF,
  32.             struct.pack('iL', bytes,interface_names.buffer_info() [0])
  33.         )
  34.         outbytes = struct.unpack('iL', sock_info) [0]
  35.         if outbytes == bytes:
  36.             max_interfaces *= 2
  37.         else:
  38.             break
  39.     namestr = interface_names.tostring()
  40.     for i in range(0, outbytes, struct_size):
  41.         interfaces.append((namestr[i:i+16].split('\0', 1)[0]))
  42.         return interfaces
  43.  
  44. if __name__ == '__main__':
  45.     interfaces = list_interfaces()
  46.     print "This machine has %s network interfaces: %s." %(len(interfaces), interface)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement