Skip to content
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

Use StatusOr in util::GetPeerAddr #1688

Merged
merged 3 commits into from
Aug 22, 2023
Merged
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
17 changes: 7 additions & 10 deletions src/common/io_util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -272,29 +272,26 @@ StatusOr<std::string> SockReadLine(int fd) {
return std::string(line.get(), line.length);
}

int GetPeerAddr(int fd, std::string *addr, uint32_t *port) {
addr->clear();

StatusOr<std::tuple<std::string, uint32_t>> GetPeerAddr(int fd) {
sockaddr_storage sa{};
socklen_t sa_len = sizeof(sa);
if (getpeername(fd, reinterpret_cast<sockaddr *>(&sa), &sa_len) < 0) {
return -1;
return Status::FromErrno("Failed to get peer name");
}

if (sa.ss_family == AF_INET6) {
char buf[INET6_ADDRSTRLEN];
auto sa6 = reinterpret_cast<sockaddr_in6 *>(&sa);
inet_ntop(AF_INET6, reinterpret_cast<void *>(&sa6->sin6_addr), buf, INET_ADDRSTRLEN);
addr->append(buf);
*port = ntohs(sa6->sin6_port);
} else {
return {buf, ntohs(sa6->sin6_port)};
} else if (sa.ss_family == AF_INET) {
auto sa4 = reinterpret_cast<sockaddr_in *>(&sa);
char buf[INET_ADDRSTRLEN];
inet_ntop(AF_INET, reinterpret_cast<void *>(&sa4->sin_addr), buf, INET_ADDRSTRLEN);
addr->append(buf);
*port = ntohs(sa4->sin_port);
return {buf, ntohs(sa4->sin_port)};
}
return 0;

return {Status::NotOK, "Failed to get peer name due to invalid family type"};
}

int GetLocalPort(int fd) {
Expand Down
2 changes: 1 addition & 1 deletion src/common/io_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ Status SockSend(int fd, const std::string &data);
StatusOr<std::string> SockReadLine(int fd);
Status SockSendFile(int out_fd, int in_fd, size_t size);
Status SockSetBlocking(int fd, int blocking);
int GetPeerAddr(int fd, std::string *addr, uint32_t *port);
StatusOr<std::tuple<std::string, uint32_t>> GetPeerAddr(int fd);
int GetLocalPort(int fd);
bool IsPortInUse(uint32_t port);

Expand Down
5 changes: 2 additions & 3 deletions src/server/worker.cc
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,8 @@ void Worker::newTCPConnection(evconnlistener *listener, evutil_socket_t fd, sock
return;
}

std::string ip;
uint32_t port = 0;
if (util::GetPeerAddr(fd, &ip, &port) == 0) {
if (auto s = util::GetPeerAddr(fd)) {
auto [ip, port] = std::move(*s);
conn->SetAddr(ip, port);
}

Expand Down