From 6691ef5a4482673c8031c3bb1d027e609e1b4b6c Mon Sep 17 00:00:00 2001 From: brapru Date: Fri, 7 Oct 2022 13:36:02 -0400 Subject: [PATCH] route: Accept CIDR notation when specifying network Now that the IPv4Address has the ability to generate valid IP addresses from CIDR notations, this provides a nicer interface to the user when specifying the network address to add or delete. --- Userland/Utilities/route.cpp | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/Userland/Utilities/route.cpp b/Userland/Utilities/route.cpp index b7c78671296..efe0aedf3d0 100644 --- a/Userland/Utilities/route.cpp +++ b/Userland/Utilities/route.cpp @@ -157,8 +157,18 @@ ErrorOr serenity_main(Main::Arguments arguments) if (!value_host_address.is_empty()) destination = AK::IPv4Address::from_string(value_host_address); - if (!value_network_address.is_empty()) - destination = AK::IPv4Address::from_string(value_network_address); + StringView address; + StringView cidr; + if (!value_network_address.is_empty()) { + // Check if a CIDR notation was provided and parse accordingly + if (auto position = value_network_address.find('/'); position.has_value()) { + address = value_network_address.substring_view(0, position.value()); + cidr = value_network_address.substring_view(position.value() + 1); + } else { + address = value_network_address; + } + destination = AK::IPv4Address::from_string(address); + } if (!destination.has_value()) { warnln("Invalid destination IPv4 address"); @@ -171,7 +181,12 @@ ErrorOr serenity_main(Main::Arguments arguments) return 1; } - auto genmask = AK::IPv4Address::from_string(value_netmask_address); + Optional genmask; + if (auto cidr_int = cidr.to_int(); cidr_int.has_value()) + genmask = AK::IPv4Address::netmask_from_cidr(cidr_int.value()); + else + genmask = AK::IPv4Address::from_string(value_netmask_address); + if (!genmask.has_value()) { warnln("Invalid genmask IPv4 address: '{}'", value_netmask_address); return 1;