Select exported routes by longest prefix
Apply a documented route-selection policy while preserving equal-cost alternatives.
Specificity comes before metric
A route covers a destination when the destination address belongs to its prefix. Under this teaching policy, choose the longest matching prefix first, then the lowest metric among those routes. A default route with metric zero does not beat a more specific /24 merely because its number is smaller.
Keep all remaining equal-cost routes rather than letting input order choose an arbitrary winner. Return them in normalized ID order. This makes the tie behavior explicit and reproducible. Real routers can have additional selection rules such as administrative distance; this exercise intentionally models only the declared exported policy.
Validate the whole route set
Normalize route IDs, VRF labels and interface identifiers. Parse prefixes strictly and require nonnegative integer metrics, excluding Boolean values. A next hop is either None for an on-link route or a valid unscoped address of the same family as its prefix.
Only matching VRF and address-family routes can be candidates, but malformed records anywhere in the supplied route list must still raise an error. Otherwise invalid out-of-scope data might remain hidden until another query happens to use it.
A selected exported route is evidence of a planned or observed forwarding entry. It does not prove end-to-end reachability, a working next hop or a successful connection. No packets leave the browser during selection.
from ipaddress import ip_address, ip_network
destination = ip_address("192.0.2.42")
for prefix in ["0.0.0.0/0", "192.0.2.0/24", "192.0.2.32/27"]:
network = ip_network(prefix)
print(network, destination in network, network.prefixlen)
Put it into practice.
Define select_routes(destination, routes, vrf). Destination is an unscoped IP string; normalize it and strip/casefold IDs, VRF, interfaces. Routes contain unique id, vrf, prefix, metric, next_hop, interface. Require nonempty identifiers, strict valid prefixes, nonnegative integer metric (not bool), and next_hop None or an unscoped address matching prefix family. Validate every row, even outside scope; invalid data raises ValueError. Choose matching VRF/family routes by longest prefix, then lowest metric. Return all ties sorted by ID as id, prefix, next_hop, interface, metric with canonical addresses. Return [] without a match and preserve inputs.
See an explained solution
from ipaddress import ip_address, ip_network
def select_routes(destination, routes, vrf):
if not isinstance(destination,str) or "%" in destination:
raise ValueError("Use an unscoped destination")
address = ip_address(destination.strip())
scope = vrf.strip().casefold()
if not scope:
raise ValueError("VRF is empty")
candidates, seen = [], set()
for row in routes:
identifier, context = row["id"].strip().casefold(), row["vrf"].strip().casefold()
interface, metric = row["interface"].strip().casefold(), row["metric"]
if not identifier or not context or not interface or identifier in seen or type(metric) is not int or metric < 0 or "%" in row["prefix"]:
raise ValueError("Invalid or duplicate route")
prefix = ip_network(row["prefix"].strip(),strict=True)
gateway = row["next_hop"]
if gateway is not None:
if not isinstance(gateway,str) or "%" in gateway:
raise ValueError("Invalid next hop")
gateway = ip_address(gateway.strip())
if gateway.version != prefix.version:
raise ValueError("Next-hop family mismatch")
seen.add(identifier)
if context == scope and address.version == prefix.version and address in prefix:
candidates.append((prefix.prefixlen,metric,{"id":identifier,"prefix":str(prefix),"next_hop":str(gateway) if gateway is not None else None,"interface":interface,"metric":metric}))
if not candidates:
return []
length = max(row[0] for row in candidates)
metric = min(row[1] for row in candidates if row[0] == length)
return sorted([row[2] for row in candidates if row[0] == length and row[1] == metric],key=lambda row:row["id"])
if __name__ == "__main__":
print(select_routes("192.0.2.9", [{"id":"local","vrf":"blue","prefix":"192.0.2.0/24","metric":10,"next_hop":None,"interface":"lan0"}], "blue"))
The selector makes precedence explicit and does not confuse a cheaper default with a more specific route. Equal-cost alternatives remain visible instead of depending on export order.