Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
2.1 kB
2
Indexable
def is_valid_ip(ip_address):
    parts = ip_address.split(".")
    if len(parts) != 4:
        return False
    for part in parts:
        if not part.isdigit():
            return False
        num = int(part)
        if num < 0 or num > 255:
            return False
    return True
def classify_ip(ip_address):
    first_octet = int(ip_address.split(".")[0])
    if 0 <= first_octet <= 127:
        return "Class A", "255.0.0.0"
    elif 128 <= first_octet <= 191:
        return "Class B", "255.255.0.0"
    elif 192 <= first_octet <= 223:
        return "Class C", "255.255.255.0"
    elif 224 <= first_octet <= 239:
        return "Class D", "Reserved"
    elif 240 <= first_octet <= 255:
        return "Class E", "Reserved"
    else:
        return "Invalid", "N/A"
def ip_to_binary(ip_address):
    return ''.join([f'{int(octet):08b}' for octet in ip_address.split('.')])
def binary_to_ip(binary_str):
    return '.'.join([str(int(binary_str[i:i+8], 2)) for i in range(0, 32, 8)])
def calculate_first_last_ip(ip_address, subnet_mask):
    ip_binary = int(ip_to_binary(ip_address), 2)
    mask_binary = int(ip_to_binary(subnet_mask), 2)

    first_ip_binary = ip_binary & mask_binary
    last_ip_binary = first_ip_binary | (~mask_binary & 0xFFFFFFFF)

    first_ip = binary_to_ip(f'{first_ip_binary:032b}')
    last_ip = binary_to_ip(f'{last_ip_binary:032b}')

    return first_ip, last_ip
def get_ip_address():
    while True:
        ip_address = input("Please enter an IP address: ")
        if is_valid_ip(ip_address):
            return ip_address
        else:
            print("Invalid IP address. Please try again.")
# Example usage
ip = get_ip_address()
ip_class, subnet_mask = classify_ip(ip)
print(f"The entered IP address is: {ip}")
print(f"IP Class: {ip_class}")
print(f"Subnet Mask: {subnet_mask}")

if ip_class in ["Class A", "Class B", "Class C"]:
    first_ip, last_ip = calculate_first_last_ip(ip, subnet_mask)
    print(f"First IP Address: {first_ip}")
    print(f"Last IP Address: {last_ip}")
else:
    print("IP address belongs to a reserved class.")

Leave a Comment