Use Python script to determine if the hostname belongs to a specific network.

Python script

Use the following Python script to check if the hostname belongs to a specific network.

#!/usr/bin/env python3
# Check if hostname belongs to network
#
# Parameters:
#   network
#   hostname
#
# Return values:
#   0 - true
#   1 - false
import ipaddress
import socket
import argparse
# define and parse command-line options
parser = argparse.ArgumentParser(description='Check if hostname belongs to specified network')
parser.add_argument('--hostname', required=True, default='10.0.0.2', help='Define hostname')
parser.add_argument('--network', required=True, default='10.0.0.0/24', help='Define network`')
args = vars(parser.parse_args())

# parse hostname
try:
    ip_address=socket.gethostbyname(args['hostname'])
except:
    print("Error: Incorrect hostname")
    exit(11)
# parse network
try:
    ip_network = ipaddress.ip_network(args['network'])
except:
    print("Error: Incorrect network")
    exit(12)

# display result
if ipaddress.ip_address(ip_address) in ipaddress.ip_network(ip_network):
    print("[+] Host " + args['hostname'] + " [" + ip_address + "] does belong to " + args['network'])
    exit(0)
else:
    if args['hostname'] != ip_address:
        print("[-] Host " + args['hostname'] + " [" + ip_address + "] does not belong to " + args['network'])
    else:
        print("[-] Host " + args['hostname'] + " does not belong to " + args['network'])
    exit(1)

Sample usage

Determine if example.com belongs to 10.0.0.0/16 network.

$ python checkipnet.py --network 10.0.0.0/16 --hostname example.com
[-] Host example.com [93.184.216.34] does not belong to 10.0.0.0/16

Determine if 172.16.11.9 belongs to 172.16.11.0/24 network.

$ python checkipnet.py --network 172.16.11.0/24 --hostname 172.16.11.9
[+] Host 172.16.11.9 does belong to 172.16.11.0/24