How to convert netmask to wildcard with netaddr python library?

555 views Asked by At

I want to convert netmask to wildcard mask with netaddr library

so the input is netmask = 255.255.255.0 and the output is wildcard = 0.0.0.255

or the input is netmask = 255.255.255.252 and the output is wildcard = 0.0.0.3

2

There are 2 answers

2
pyjedy On

netaddr not support non-contiguous wildcard but cisco-acl can help to play with wildcard

from cisco_acl import AddressAg

address = AddressAg("0.0.0.0 255.255.255.0")
mask = address.subnet.split()[1]
wildmask = address.wildcard.split()[1]
print(mask)  # 255.255.255.0
print(wildmask)  # 0.0.0.255
0
Andrew On

Normally, all netmask octets are one of nine possible values "0", "255", "192", "224", "240", "248", "252", "254", or "255". Given this, a simple solution is:

netmask.replace("0", "255").replace("128", "127").replace("192", "63").replace("224", "31").replace("240", "15").replace("248", "7").replace("252", "3").replace("254", "0").replace("255", "0")