pythonsockets

What is the use of 0x8915?


I don't understand how the code in get_ip_address() helps in getting the IP address of the given interface. Also, what is the significance of the value 0x8915 as the second argument to fcntl.ioctl()?

#!/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

Solution

  • 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.