1

# I am not understanding how does the code followed by return statement help in getting ip address of the given interface and what is the use of 0x8915??

 #!/usr/bin/env python

 import argparse
 import sys
 import fcntl
 import struct
 import array
 import socket

 def get_ip_address(ifname):
   #interfaces = list_interfaces()
   s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
   return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915,  
 struct.pack('256s', ifname[:15]))[20:24])

 if __name__ == '__main__':
   parser = argparse.ArgumentParser(description='Python 
 networkingutils')
   parser.add_argument('--ifname', action="store", dest="ifname", 
 required=True)
   given_args = parser.parse_args()
   ifname = given_args.ifname
   print "Interface [%s] --> IP: %s" %(ifname, get_ip_address(ifname))


The output of this script is shown in one line, as follows:
$ python 3_5_get_interface_ip_address.py --ifname=eth0
Interface [eth0] --> IP: 10.0.2.15
    -

1 Answers1

1

0x8915 is the value for Linux SIOCGIFADDR. Unfortunately it is hard coded in this python code and without any comments which impacts readability of the code. SIOCGIFADDR is used within ioctl to get the IP address for an interface. See this documentation for more information or look at this code which is a more readable version in C than the python code you cite.

Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172