Skip to content

Instantly share code, notes, and snippets.

@shufengh
Created April 4, 2025 04:17
Show Gist options
  • Save shufengh/05d505ebf0f2f85c58dfb0b1d991f141 to your computer and use it in GitHub Desktop.
Save shufengh/05d505ebf0f2f85c58dfb0b1d991f141 to your computer and use it in GitHub Desktop.
convert between cidr and subnet
import sys
def cidr_to_subnet(ip_cidr):
"""Convert IP/CIDR format to IP Subnet Mask format."""
ip, cidr = ip_cidr.split('/')
cidr = int(cidr)
mask = ((1 << cidr) - 1) << (32 - cidr)
subnet_mask = ".".join(str((mask >> i) & 0xff) for i in [24, 16, 8, 0])
return "{} {}".format(ip, subnet_mask)
def subnet_to_cidr(ip_subnet):
"""Convert IP Subnet Mask format to IP/CIDR format."""
ip, subnet = ip_subnet.split(None, 1)
subnet_parts = map(int, subnet.split('.'))
cidr = sum(bin(part).count('1') for part in subnet_parts)
return "{}/{}".format(ip, cidr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment