2017-08-26 56 views
1

#我不理解返回語句 後得到的代碼如何幫助獲取給定接口的ip地址以及0x8915的使用 是什麼?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 
    -
+0

只需在交互式解釋器中輸入「0x8915」並查看。還可以嘗試「0x1」,「0x10」或「0xff」。 –

+0

0x8915是35093 – Inconnu

+0

fcntl.ioctl()有什麼用? –

回答

1

0x8915是Linux SIOCGIFADDR值。不幸的是,它在這個python代碼中被硬編碼,沒有任何影響代碼可讀性的註釋。在ioctl中使用SIOCGIFADDR來獲取接口的IP地址。有關更多信息,請參見this documentation或查看this code,這是C中比您引用的Python代碼更易讀的版本。