How to do it...

You can use the fnctl module to query the IP address on your machine.

Listing 3.5 shows us how to find the IP address for a specific interface on your machine, as follows:

#!/usr/bin/env python 
# Python Network Programming Cookbook, Second Edition -- Chapter - 3 
# This program is optimized for Python 2.7.12 and Python 3.5.2. 
# It may run on any other version with/without modifications. 
 
import argparse 
import sys 
import socket 
import fcntl 
import struct 
import array 
 
 
def get_ip_address(ifname): 
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    return socket.inet_ntoa(fcntl.ioctl( 
        s.fileno(), 
        0x8915,  # SIOCGIFADDR 
        struct.pack(b'256s', bytes(ifname[:15], 'utf-8')) 
    )[20:24]) 
 
if __name__ == '__main__': 
    parser = argparse.ArgumentParser(description='Python 
networking utils') 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=lo
Interface [lo] --> IP: 127.0.0.1 
  

In the preceding execution, make sure to use an existing interface, as printed in the previous recipe. In my computer, I got the output previously for 3_4_list_network_interfaces.py:

This machine has 2 network interfaces: ['lo', 'wlo1'].
  

If you use a non-existing interface, an error will be printed.

For example, I do not have eth0 interface right now. So the output is:

$ python3 3_5_get_interface_ip_address.py --ifname=eth0 
Traceback (most recent call last):
File "3_5_get_interface_ip_address.py", line 27, in <module>
  print ("Interface [%s] --> IP: %s" %(ifname, get_ip_address(ifname)))       
  File "3_5_get_interface_ip_address.py", line 19, in get_ip_address
  struct.pack(b'256s', bytes(ifname[:15], 'utf-8'))
OSError: [Errno 19] No such device
  
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.68.159