Skip to content

Commit

Permalink
Use StatusOr in util::GetPeerAddr (#1688)
Browse files Browse the repository at this point in the history
  • Loading branch information
PragmaTwice authored Aug 22, 2023
1 parent 54423b6 commit f9f93fb
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 14 deletions.
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

0 comments on commit f9f93fb

Please sign in to comment.