Skip to content

Commit

Permalink
Fix sockets with invalid address
Browse files Browse the repository at this point in the history
  • Loading branch information
dallison committed Jan 30, 2024
1 parent dbe2e83 commit a93a5d1
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
6 changes: 6 additions & 0 deletions toolbelt/sockets.cc
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

#include <algorithm>
#include <string>
#include <iostream>

#include "absl/strings/str_format.h"
#include "hexdump.h"
Expand All @@ -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),
Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -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<const sockaddr *>(&addr.GetAddress()),
addr.GetLength());
Expand Down
4 changes: 2 additions & 2 deletions toolbelt/sockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -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_); }
Expand Down Expand Up @@ -234,4 +234,4 @@ class TCPSocket : public NetworkSocket {
};
} // namespace toolbelt

#endif // __TOOLBELT_SOCKETS_H
#endif // __TOOLBELT_SOCKETS_H

0 comments on commit a93a5d1

Please sign in to comment.