KingVince
KingVince

Reputation: 33

calculate the address of the subnet in Python

My code:

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

    ip_1 = int(ip[0])
    ip_2 = int(ip[1])
    ip_3 = int(ip[2])
    ip_4 = int(ip[3])

    net_1 = int(net[0])
    net_2 = int(net[1])
    net_3 = int(net[2])
    net_4 = int(net[3])

    print(f"{ip_1 & net_1} {ip_2 & net_2} {ip_3 & net_3} {ip_4 & net_4}")

Result:

192 0 0 0

What I need is this:

192.0.0.0

or

"192.0.0.0"

My code

Upvotes: 0

Views: 64

Answers (1)

Liju
Liju

Reputation: 2313

As already mentioned in the comment, you can add '.' in your print format.

And it is not recommended to assign list items into individual variable.
You can accomplish this with below code instead

def apply_network_mask(host_address, netmask):
    print('.'.join([str(int(a)&int(b)) for a,b in zip(host_address.split('.'),netmask.split('.'))]))

Upvotes: 1

Related Questions