12 months

IP and DNS

The IP address labels a machine's network interface with a numeric identifier, which also identifies the location of the machine, albeit with limited reliability. Domain Name System (DNS) is a core network service that maps the names to the IP addresses and vice-verse. Network Time Protocol (NTP) helps in synchronizing the time with a centralized time server. 

Retrieving the network configuration of a local machine 

On the shell command-line, this can be discovered by using the hostnamecommand. In Python, you can do this by using the socket module.

>>> import socket            
>>> socket.gethostname()

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:                                                                         
ipaddrs = netifaces.ifaddresses(iface)                                           
 if netifaces.AF_INET in ipaddrs:                                                   
 ipaddr_desc = ipaddrs[netifaces.AF_INET]                                  
 ipaddr_desc = ipaddr_desc[0]                                                       
 print("Network interface: {0}".format(iface))                                   
 print("\tIP address: {0}".format(ipaddr_desc['addr']))                     
 print("\tNetmask: {0}".format(ipaddr_desc['netmask']))                  
 # Find the gateway                                                                         
 gateways = netifaces.gateways()                                                   
 print("Default gateway:                                                                   

Manipulating IP addresses

Python3 has a built-in ipaddress module to help you in carrying out to manipulate IP addresses and perform some sort of operations on them.  It has convenient functions for defining the IP addresses and the IP networks and for finding lots of useful information. This module will provide several classes and factory functions; for example, the IP address and the IP network has separate classes. Each class has a variant for both IP version 4 (IPv4) and IP version 6 (IPv6).

>>> import ipaddress as ip                                                       
>>> net4 = ip.ip_network('')                                    
>>> net4.netmask                                                                    
>>> str(net4.netmask)                                                              
>>> str(net4.network_address)                                                
>>> str(net4.broadcast_address)                                             
>>> net4.num_addresses   (show total addresses)                
>>> all_hosts = list(net4.hosts())                                             
>>> len(all_hosts)                                                                   
>>> subnets = list( net4.subnets())  ( subnet information)      
>>> subnets                                                                           
>>> net4.supernet()                                                               

In the ipaddress module, a convenient class is used for representing an interface's IP configuration in detail. The IPv4 Interface class takes an arbitrary address and behaves like a network address object. 

The IP address classes have many more interesting properties. You can perform some arithmetic and logical operations on those objects. For example, if an IP address is greater than another IP address, then you can add numbers to the IP address objects, and this will give you a corresponding IP address. 

GeoIP look-ups

At times, it will be necessary for many applications to look-up the location of the IP addresses. There is a third-party library called python-geoip, which has a robust interface for giving you the answer to your IP location query. This library is provided by MaxMind, which also provides the option for shipping a recent version of the Geolite2 database as the python-geoip-geolite2 package. This includes the GeoLite2 data created by MaxMind, which is available at www.maxmind.com under the creative commons Attribution-ShareAlike 3.0 Unported  License. You can also buy a commercial license from their website.

import socket                                                                                                              
from geoip import geolite2                                                                                         
import argparse                                                                                                          
if __name__ == '__main__':                                                                                       
 # Setup commandline arguments                                                                             
 parser = argparse.ArgumentParser(description='Get IP Geolocation info')               
 parser.add_argument('--hostname', action="store", dest="hostname", required=True)
 # Parse arguments                                                                                                      
 given_args = parser.parse_args()                                                                               
 hostname = given_args.hostname                                                                              
 ip_address = socket.gethostbyname(hostname)                                                        
 print("IP address: {0}".format(ip_address))                                                                 
 match = geolite2.lookup(ip_address)                                                                          
 if match is not None:                                                                                                  
 print('Country: ',match.country)                                                                                  
 print('Continent: ',match.continent)                                                                             
 print('Time zone: ', match.timezone)                                                                           

DNS look-ups
The IP address can be translated into human readable strings called domain names. We will use the dnspython library, which is available at http://www.dnspython.org/.

$ pip install dnspython                                                                                  

import dns.resolver                                                                                        
answers = dns.resolver.query('python.org', 'A')                                              

import dns.reversename
name = dns.reversename.from_address("")  (a reverse look-up)

import dns.resolver
if __name__ == '__main__':
 loookup_continue = True
 while loookup_continue:
    name = input('Enter the DNS name to resolve: ')
    record_type = input('Enter the query type  [A/MX/CNAME]: ')
    answers = dns.resolver.query(name, record_type)
    if record_type == 'A':
     print('Got answer IP address: %s' %[x.to_text() for x  in answers])
   elif record_type == 'CNAME':
     print('Got answer Aliases: %s' %[x.to_text() for x in  answers])
   elif record_type == 'MX':
     for rdata in answers:
        print('Got answers for Mail server records:')
        print('Mailserver', rdata.exchange.to_text(), 'has  preference', rdata.preference)
        print('Record type: %s is not implemented'  %record_type)
 lookup_more = input("Do you want to lookup more  records? [y/n]: " )
 if lookup_more.lower() == 'n':
     loookup_continue = False

Network Time Protocol clients

Synchronizing time with a centralized time server is a key step in any corporate network.Many authentication protocols, such as Kerberos, strictly rely on the accuracy of the time stamp reported by the client to the servers. 

import ntplib                                                                 
from time import ctime                                                 
HOST_NAME = 'pool.ntp.org'                                      
if __name__ == '__main__':                                           
 params = {}                                                                      
 client = ntplib.NTPClient()                                                 
 response = client.request(HOST_NAME)                         
 print('Received time: %s' %ctime(response.tx_time))        
 print('ref_clock: ',ntplib.ref_id_to_text(response.ref_id,       
 print('stratum: ',response.stratum)                                   
 print('last_update: ', response.ref_time)                        
 print('offset: %f' %response.offset)                                
 print('precision: ', response.precision)                            
 print('root_delay: %.6f' %response.root_delay)               
 print('root_dispersion: %.6f' %response.root_dispersion)

For more information about the NTP protocol, you may either read the RFC 958 document at https://tools.ietf.org/html/rfc958 or visit http://www.ntp.org/.