Learning Python Network Programming

(Sean Pound) #1

IP and DNS


Now, we would like to see the local machine IP. This can be seen by using the
ifconfig command in Linux and by using the ipconfig command in the Windows
OS. But, we'd like to do this in Python by using the following built-in function:





socket.gethostbyname('debian6box.localdomain.loc')





'10.0.2.15'


As you can see, this is the IP of the first network interface. It can also show us the IP
of the loopback interface (127.0.0.1) if your DNS or hostfile has not been configured
properly. In Linux/UNIX, the following line can be added to your /etc/hosts file
for obtaining the correct IP address:


10.0.2.15 debian6box.localdomain.loc debian6box

This process is known as a host-file based name resolution. You can send a query
to a DNS server and ask for the IP address of a specific host. If the name has been
registered properly, then you will get a response from the server. But, before making
a query to the remote server, let us first discover some more information about the
network interface and the gateway machine of your network.


In every LAN, a host is configured to act as a gateway, which talks to the outside
world. In order to find the network address and the netmask, we can use the
Python third-party library netifaces (version > 0.10.0 ). This will pull all the relevant
information. For example, you can call netifaces.gateways() for finding the
gateways that are configured to the outside world. Similarly, you can enumerate
the network interfaces by calling netifaces.interfaces(). If you would like to
know all the IP addresses of a particular interface eth0, then you can call netifaces.
ifaddresses('eth0'). The following code listing shows the way in which you can
list all the gateways and IP addresses of a local machine:


#!/usr/bin/env python
import socket
import netifaces

if __name__ == '__main__':
# Find host info
host_name = socket.gethostname()
ip_address = socket.gethostbyname(host_name)
print("Host name: {0}".format(host_name))

# Get interfaces list
ifaces = netifaces.interfaces()
for iface in ifaces:
Free download pdf