Last active
July 13, 2021 03:49
-
-
Save CraigTheKiwi/83a334c721bb7d75712bdc11c0d05782 to your computer and use it in GitHub Desktop.
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
#!/bin/python3 | |
# Take an ip string and return a string representing it's binary value | |
# inputs: ip_string = '192.168.1.12' | |
# outputs: returns '1100000010...' | |
def prepBinary(ip_string): | |
binary_string = "" | |
ip_nums_string = ip_string.split("."); | |
for ip_num in ip_nums_string: | |
# creates a binary number with 8 digits .. i.e. 6 becomes 00000110, 192 becomes 11000000 | |
binary_string += ('{0:08b}'.format(int(ip_num))) | |
return binary_string | |
# Calculate whether a given ip needle is in an ip haystack range | |
# inputs: needle = ip string i.e. '192.168.1.21" | |
# haystack= ip string with mask i.e. '192.168.1.1/24' | |
# outputs: boolean | |
def inRange(needle, haystack): | |
# prep haystack: | |
# - split off the network mask | |
haystack_parts = haystack.split("/") | |
haystack_mask = int(haystack_parts[1]) | |
# - convert the ip addresses to binary representations | |
# i.e. haystack_binary = 11000000101010000000000000000000 | |
# needle_binary = 11000000101010000000010000011011 | |
haystack_binary = prepBinary(haystack_parts[0]) | |
needle_binary = prepBinary(needle) | |
# count along {mask} number of items from left to right and check they match .... | |
if needle_binary[0:haystack_mask] == haystack_binary[0:haystack_mask]: | |
return "true" | |
return "false" | |
if __name__ == "__main__": | |
# If I was going to get carried away, I'd check ip string inputs before passing them | |
print(inRange("192.168.4.27", "192.168.0.0/16")) | |
print(inRange("192.168.4.27", "192.168.1.0/24")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment