Skip to content

Instantly share code, notes, and snippets.

@hpreston
Last active November 13, 2019 22:13
Show Gist options
  • Save hpreston/1d76db2d9efa82bffcb471a7034d33d4 to your computer and use it in GitHub Desktop.
Save hpreston/1d76db2d9efa82bffcb471a7034d33d4 to your computer and use it in GitHub Desktop.
Create Wildcard Mask
# Simple function to create a wildcard mask from a subnet mask
def wildcard_mask(netmask):
# Ensure netmask provided is a basic string (ie not an IPv4Address)
netmask = str(netmask)
# Break into a list of octets as integers
netmask_list = map(int, netmask.split("."))
# Use XOR to "invert" each octect
wildcard_list = [ 255^octet for octet in netmask_list ]
# Join wildcard octets into a single wildcard mask string
wildcard_mask = ".".join(map(str,wildcard_list))
return wildcard_mask
# Alternative using IPv4Address math (thanks to simingy)
def wildcard_mask2(netmask):
host_mask = ipaddress.IPv4Address("255.255.255.255")
my_subnet = ipaddress.IPv4Address(netmask)
wildcard_mask = host_mask - int(my_subnet)
return wildcard_mask
# Sample usage
wildcard_mask("255.255.255.0")
wildcard_mask("255.255.255.248")
import ipaddress
mynetwork = ipaddress.ip_network("192.168.23.0/27")
wildcard_mask(mynetwork.netmask)
# And continuing to make it even easier... @plajjan mentioned this gem
wildcard_mask = ipaddress.ip_network("10.1.0.0/22").hostmask
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment