[python]Auto discover your laptop’s interface ip address belongs to which subnet

The use case for this is I want to create an automated pentest when my laptop is connected to the network.
When my laptop connects to a network, the directed connected network is scanned for host running on which ports, then the ports are evaluated to check if it is vulnerable to EternalBlue, if it is vulnerable test the exploits.

Hence this piece of code is meant to auto discover which network my pentest laptop belongs to in order to evaluate the network for vulnerabilities.

from netifaces import interfaces, ifaddresses
from ipaddress import IPv4Interface

# Refer to doc https://pypi.org/project/netifaces/
# interfaces method returns a list of interface.
# ifaddresses method returns a dictionary on specific interface.
# 18 returns layer 2 information i.e. mac address.
# 2 returns layer 3 information i.e. IP address.
# Hence I am only interested if any interfaces in my computer has a valid IP address.
# Then I use another if loop to filter away localhost address.
# The information is structured in a dictionary for easy manipulation.
def check_local_valid_address():
    available_interfaces = interfaces()
    for interface in available_interfaces:
        if ifaddresses(interface).get(2):
            if ifaddresses(interface).get(2)[0].get('addr') != '':
                intf = interface
                intf_ip = ifaddresses(interface).get(2)[0].get('addr')
                intf_netmask = ifaddresses(interface).get(2)[0].get('netmask')
                return {'interface': intf,
                        'ip_address': intf_ip,
                        'netmask': intf_netmask}

# See demonstration in https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Interface
# Under network section.
# The result will return an IPv4Address object hence I use str() to convert to string object.
def address_belongs_to_which_subnet(host_address):
    return str(IPv4Interface(host_address).network)

# count the number of 1 in the binary representation of 255, 254, 252, 248, 240, 224, 192, 128
# refer to this https://stackoverflow.com/questions/38085571/how-use-netaddr-to-convert-subnet-mask-to-cidr-in-python
# credit goes to Eugene Yarmash who replied in the post.
def convert_subnet_to_cidr(subnet_mask):
    return (sum(bin(int(x)).count('1') for x in subnet_mask.split('.')))

# Test the functions here.
if __name__ == '__main__':
    interface_info = check_local_valid_address()
    cidr = str(convert_subnet_to_cidr(interface_info['netmask']))
    subnet = address_belongs_to_which_subnet(interface_info['ip_address'] + '/' + cidr)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s