TransWikia.com

Calculate the address of the subnet

Stack Overflow Asked by KingVince on January 19, 2021

Calculate the address of the subnet:

COMMAND:
If you represent the host address and netmask as lists of 4 numbers each, you may take the bitwise AND of the first number from one list and the first number from the other list, followed by the bitwise AND of the second number from the one list and the bitwise AND of the second number from the other list, and so on. Returns the address of the network as a list.

MY CODE:

def apply_network_mask(host_address, netmask):
    ips = host_address.split(".")
    net = netmask.split(".")

    ips_bin = [format(int(i), '08b') for i in ips]
    net_bin = [format(int(i), '08b') for i in net]

    print(f"{ips_bin & net_bin}")

My Code:
My Code

what I need:
apply_network_mask ([192,168,0,191], [255,255,255,0]) I should get back [192,168,0,0]

2 Answers

You can do this in one go by reading the network property of an ipaddress.ip_interface

>>> import ipaddress
>>> ipaddress.ip_interface("192.168.0.161/255.255.255.0").network
IPv4Network('192.168.0.0/24')

You can go further and directly get your network address as a string from the IPv4Network's with_netmask property

>>> ipaddress.ip_interface("192.168.0.161/255.255.255.0").network.with_netmask.split('/')
['192.168.0.0', '255.255.255.0']

This will also work for IPv6 addresses

>>> ipaddress.ip_interface("2001:0db8:85a3:0000:0000:8a2e:0370:7334/64").network
IPv6Network('2001:db8:85a3::/64')

Answered by ti7 on January 19, 2021

look at this example

from ipaddress import IPv4Address
import re


class MyIPv4(IPv4Address):
    def __and__(self, other: IPv4Address):
        if not isinstance(other, (int, IPv4Address)):
            raise NotImplementedError
        return self.__class__(int(self) & int(other))

    @property
    def binary_repr(self, sep=".") -> str:
        """Represent IPv4 in binary"""
        return sep.join(f"{i:08b}" for i in self.packed)  

    @classmethod
    def from_binary_repr(cls, binary_repr: str):
        """Represent IPv4 ifrom binary to human readable view"""
        i = int(re.sub(r"[^01]", "", binary_repr), 2)  
        return cls(i)


addr = MyIPv4("192.168.0.2")
mask = MyIPv4("255.255.255.0")


print(f'{addr} & {mask} is {addr & mask} network')
print(f'{addr.binary_repr} & {mask.binary_repr} is {(addr & mask).binary_repr} network')

source

Answered by shabelski89 on January 19, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP