Created
February 23, 2024 02:13
-
-
Save unfrgivn/f3ee759e545f8026e9630575eb3ee7b2 to your computer and use it in GitHub Desktop.
IP in CIDR Block
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
''' | |
Given an IP and a CIDR block, write a utility function to determine whether an input IP belongs to the CIDR block or not. Solution from a recent interview: | |
# Write a function to return back a boolean (true or false) given inputs of the following: | |
# 1. Candidate IP - 10.25.22.233 | |
# 2. Mask size - 22 | |
# 3. Subnet IP - 10.25.11.111 | |
''' | |
def convert_to_int(ip): | |
octets = ip.split('.') | |
return (int(octets[0]) << 24) + (int(octets[1]) << 16) + (int(octets[2]) << 8) + int(octets[3]) | |
def ip_in_cidr(candidate_ip, mask_size, subnet_ip): | |
try: | |
# split both those string into octets | |
# t = list(map(int, candidate_ip.split("."))) | |
# s = list(map(int, subnet_ip.split("."))) | |
# This is the bit operator I forgot how to use, so I looked that up | |
subnet_mask = (1 << 32) - (1 << (32 - mask_size)) | |
# Convert both dot notations the decimal representation of their binary form | |
subnet_ip_int = convert_to_int(subnet_ip) | |
candidate_ip_int = convert_to_int(candidate_ip) | |
# The bitwise & comparison will remove the last 10 bits for the mask and then | |
# compare if everything up to that point is equivalent | |
return (candidate_ip_int & subnet_mask) == (subnet_ip_int & subnet_mask) | |
except ValueError: | |
return False | |
print(ip_in_cidr("10.25.22.233", 22, "10.25.11.111")) | |
''' | |
Validating in binary notation | |
Mask 11111111 11111111 11111100 00000000 | |
Subnet 00001010 00011001 00001011 01101111 | |
Input 00001010 00011001 00010110 11101001 | |
^fail | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment