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)}")
#source code --> clcoding.com
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]}")
#source code --> clcoding.com
Network range: 192.168.1.0 - 192.168.1.255
3. Check if an IP Address is in a Specific Network
This program checks if a given IP address is part of a specified network.
import ipaddress
def ip_in_network(ip, network):
try:
network_obj = ipaddress.ip_network(network, strict=False)
ip_obj = ipaddress.ip_address(ip)
return ip_obj in network_obj
except ValueError:
return False
ip = "192.168.1.10"
network = "192.168.1.0/24"
print(f"Is {ip} in network {network}? {ip_in_network(ip, network)}")
#source code --> clcoding.com
Is 192.168.1.10 in network 192.168.1.0/24? True
4. Generate All IP Addresses in a Network
This program generates all possible IP addresses within a given network.
import ipaddress
def generate_ips_in_network(network):
try:
network_obj = ipaddress.ip_network(network, strict=False)
return [str(ip) for ip in network_obj.hosts()]
except ValueError:
return []
network = "192.168.1.0/30"
ips = generate_ips_in_network(network)
print(f"IP addresses in {network}: {ips}")
#source code --> clcoding.com
IP addresses in 192.168.1.0/30: ['192.168.1.1', '192.168.1.2']
5. Convert Integer to IPv4 Address
This program converts an integer back to its corresponding IPv4 address.
import ipaddress
def int_to_ipv4(integer):
try:
return str(ipaddress.IPv4Address(integer))
except ValueError:
return None
ipv4_int = 3232235777
print(f"Integer: {ipv4_int} -> IPv4: {int_to_ipv4(ipv4_int)}")
#source code --> clcoding.com
Integer: 3232235777 -> IPv4: 192.168.1.1
0 Comments:
Post a Comment