From f3fcbede5ce46cbcd44a7de646b375b7fa9473b8 Mon Sep 17 00:00:00 2001 From: bneradt Date: Sat, 9 Sep 2023 18:05:49 -0500 Subject: [PATCH] IPEndpoint: make ::port robust for invalid addresses We had a bwprint function throw the following for printing an adddress: "what(): sockaddr is not a valid IP address" This makes the ::port logic handle invalid (likely AF_UNSPEC) addresses. --- code/include/swoc/IPEndpoint.h | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/code/include/swoc/IPEndpoint.h b/code/include/swoc/IPEndpoint.h index cce0113..da8c98d 100644 --- a/code/include/swoc/IPEndpoint.h +++ b/code/include/swoc/IPEndpoint.h @@ -207,6 +207,9 @@ union IPEndpoint { /// Port in host horder. in_port_t host_order_port() const; + /// Test for valid IP address from @a sockaddr. + static bool is_valid(sockaddr const *sa); + /// Port in network order from @a sockaddr. static in_port_t &port(sockaddr *sa); @@ -348,6 +351,11 @@ IPEndpoint::host_order_port() const { return ntohs(this->network_order_port()); } +inline bool +IPEndpoint::is_valid(sockaddr const *sa) { + return sa && (sa->sa_family == AF_INET || sa->sa_family == AF_INET6); +} + inline in_port_t & IPEndpoint::port(sockaddr *sa) { switch (sa->sa_family) { @@ -362,12 +370,12 @@ IPEndpoint::port(sockaddr *sa) { inline in_port_t IPEndpoint::port(sockaddr const *sa) { - return self_type::port(const_cast(sa)); + return self_type::is_valid(sa) ? self_type::port(const_cast(sa)) : 0; } inline in_port_t IPEndpoint::host_order_port(sockaddr const *sa) { - return ntohs(self_type::port(sa)); + return self_type::is_valid(sa) ? ntohs(self_type::port(sa)) : 0; } inline swoc::MemSpan