438 views
0 votes
0 votes
Write a function to do forwarding in an IP router. The procedure has one parameter,
an IP address. It also has access to a global table consisting of an array of triples.
Each triple contains three integers: an IP address, a subnet mask, and the outline line
to use. The function looks up the IP address in the table using CIDR and returns the
line to use as its value.

1 Answer

0 votes
0 votes
def forward_ip_address(ip_address):
    # Global table of IP addresses, subnet masks, and output lines
    table = [
        ("10.0.0.0", "255.0.0.0", 1),
        ("172.16.0.0", "255.240.0.0", 2),
        ("192.168.1.0", "255.255.255.0", 3)
    ]
    
    # Convert IP address to integer format
    ip_int = sum([int(octet) << ((3 - i) * 8) for i, octet in enumerate(ip_address.split('.'))])
    
    # Iterate over the table and check if the IP address matches
    for addr, mask, line in table:
        # Convert address and mask to integer format
        addr_int = sum([int(octet) << ((3 - i) * 8) for i, octet in enumerate(addr.split('.'))])
        mask_int = sum([int(octet) << ((3 - i) * 8) for i, octet in enumerate(mask.split('.'))])
        
        # Check if the IP address matches using CIDR
        if (ip_int & mask_int) == (addr_int & mask_int):
            return line
    
    # If no match is found, return None
    return None
 

In this example, the function takes an IP address as its parameter and looks up the IP address in the global table using CIDR. The table is represented as an array of triples, where each triple contains an IP address, a subnet mask, and an output line.

The function first converts the input IP address to an integer format for easier comparison. Then, it iterates over the table and converts each address and mask to integer format as well. It checks if the IP address matches the table entry using CIDR by performing a bitwise AND operation between the IP address and the mask, and comparing it to the corresponding address and mask in the table. If a match is found, the function returns the output line associated with the table entry. If no match is found, the function returns None.

Related questions

0 votes
0 votes
1 answer
4
ajaysoni1924 asked Mar 18, 2019
545 views
When the IPv6 protocol is introduced, does the ARP protocol have to be changed? Ifso, are the changes conceptual or technical?