Member-only story

IP Address Manipulation with Python

Python Coding
2 min readAug 24, 2024

--

1. Check if an IP Address is Private

This program checks whether an IP address belongs to a private range.

import ipaddress

def check_private_ip(ip):
try:
ip_obj = ipaddress.ip_address(ip)
return ip_obj.is_private
except ValueError:
return False

ip = "192.168.0.1"
print(f"Is {ip} private? {check_private_ip(ip)}")
Is 192.168.0.1 private? True

2. Calculate the Network Range from a CIDR Notation

This program calculates the network range from a given CIDR notation.

import ipaddress

def get_network_range(cidr):
try:
network = ipaddress.ip_network(cidr, strict=False)
return (network.network_address, network.broadcast_address)
except ValueError:
return None

cidr = "192.168.1.0/24"
network_range = get_network_range(cidr)
if network_range:
print(f"Network range: {network_range[0]} - {network_range[1]}")
Network range: 192.168.1.0 - 192.168.1.255

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

No responses yet