Skip to content

gloo/tcp/attr: hold on to bound socket to avoid port conflict issues #429

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions gloo/transport/tcp/attr.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,30 @@
#include <string>

#include <sys/socket.h>
#include <unistd.h>
#include <memory>

namespace gloo {
namespace transport {
namespace tcp {

// RAII for fds so they'll close when all references to them are freed.
class FDHolder {
public:
explicit FDHolder(int fd) : fd_(fd) {}
~FDHolder() {
close(fd_);
}

FDHolder(const FDHolder&) = delete;
FDHolder& operator=(const FDHolder&) = delete;
FDHolder(FDHolder&&) = delete;
FDHolder& operator=(FDHolder&&) = delete;

private:
const int fd_;
};

struct attr {
attr() {}
/* implicit */ attr(const char* ptr) : hostname(ptr) {}
Expand All @@ -31,6 +50,8 @@ struct attr {
int ai_protocol;
struct sockaddr_storage ai_addr;
int ai_addrlen;

std::shared_ptr<FDHolder> fd{nullptr};
};

} // namespace tcp
Expand Down
5 changes: 4 additions & 1 deletion gloo/transport/tcp/device.cc
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@ static void lookupAddrForHostname(struct attr& attr) {
attr.ai_protocol = rp->ai_protocol;
memcpy(&attr.ai_addr, rp->ai_addr, rp->ai_addrlen);
attr.ai_addrlen = rp->ai_addrlen;
close(fd);

// We explicitly don't close this FD here as we want to hold on to it until
// the listener binds the server socket to the port.
attr.fd = std::make_shared<FDHolder>(fd);
break;
}

Expand Down
Loading