Last active
November 13, 2019 22:13
-
-
Save hpreston/1d76db2d9efa82bffcb471a7034d33d4 to your computer and use it in GitHub Desktop.
Create Wildcard Mask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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