From a93a5d1ac8e4a6c8447602e29781ad6d20dd22bd Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Mon, 29 Jan 2024 18:03:30 -0800 Subject: [PATCH] Fix sockets with invalid address --- toolbelt/sockets.cc | 6 ++++++ toolbelt/sockets.h | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/toolbelt/sockets.cc b/toolbelt/sockets.cc index 9135b84..7c36146 100644 --- a/toolbelt/sockets.cc +++ b/toolbelt/sockets.cc @@ -13,6 +13,7 @@ #include #include +#include #include "absl/strings/str_format.h" #include "hexdump.h" @@ -26,6 +27,7 @@ InetAddress InetAddress::BroadcastAddress(int port) { InetAddress InetAddress::AnyAddress(int port) { return InetAddress(port); } InetAddress::InetAddress(const in_addr &ip, int port) { + valid_ = true; addr_ = { #if defined(_APPLE__) .sin_len = sizeof(int), @@ -58,6 +60,7 @@ InetAddress::InetAddress(const std::string &hostname, int port) { if (inet_pton(AF_INET, hostname.c_str(), &ipaddr) != 1) { fprintf(stderr, "Invalid IP address or unknown hostname %s\n", hostname.c_str()); + valid_ = false; return; } } @@ -420,6 +423,9 @@ absl::Status NetworkSocket::Connect(const InetAddress &addr) { if (!fd_.Valid()) { return absl::InternalError("Socket is not valid"); } + if (!addr.Valid()) { + return absl::InternalError("Bad InetAddress"); + } int e = ::connect(fd_.Fd(), reinterpret_cast(&addr.GetAddress()), addr.GetLength()); diff --git a/toolbelt/sockets.h b/toolbelt/sockets.h index f677061..01c3303 100644 --- a/toolbelt/sockets.h +++ b/toolbelt/sockets.h @@ -39,7 +39,7 @@ class InetAddress { InetAddress(const std::string &hostname, int port); // An address from a pre-constructed socket address in network order. - InetAddress(const struct sockaddr_in &addr) : addr_(addr) {} + InetAddress(const struct sockaddr_in &addr) : addr_(addr), valid_(true) {} const sockaddr_in &GetAddress() const { return addr_; } socklen_t GetLength() const { return sizeof(addr_); } @@ -234,4 +234,4 @@ class TCPSocket : public NetworkSocket { }; } // namespace toolbelt -#endif // __TOOLBELT_SOCKETS_H \ No newline at end of file +#endif // __TOOLBELT_SOCKETS_H