From f9f93fbbd8684d0d111c0624d41301c2ff669e30 Mon Sep 17 00:00:00 2001 From: Twice Date: Tue, 22 Aug 2023 11:22:57 +0800 Subject: [PATCH] Use StatusOr in util::GetPeerAddr (#1688) --- src/common/io_util.cc | 17 +++++++---------- src/common/io_util.h | 2 +- src/server/worker.cc | 5 ++--- 3 files changed, 10 insertions(+), 14 deletions(-) diff --git a/src/common/io_util.cc b/src/common/io_util.cc index cb30a48047b..b4779f86ba6 100644 --- a/src/common/io_util.cc +++ b/src/common/io_util.cc @@ -272,29 +272,26 @@ StatusOr SockReadLine(int fd) { return std::string(line.get(), line.length); } -int GetPeerAddr(int fd, std::string *addr, uint32_t *port) { - addr->clear(); - +StatusOr> GetPeerAddr(int fd) { sockaddr_storage sa{}; socklen_t sa_len = sizeof(sa); if (getpeername(fd, reinterpret_cast(&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(&sa); inet_ntop(AF_INET6, reinterpret_cast(&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(&sa); char buf[INET_ADDRSTRLEN]; inet_ntop(AF_INET, reinterpret_cast(&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) { diff --git a/src/common/io_util.h b/src/common/io_util.h index 8391d2cc129..9ab288aed31 100644 --- a/src/common/io_util.h +++ b/src/common/io_util.h @@ -35,7 +35,7 @@ Status SockSend(int fd, const std::string &data); StatusOr 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> GetPeerAddr(int fd); int GetLocalPort(int fd); bool IsPortInUse(uint32_t port); diff --git a/src/server/worker.cc b/src/server/worker.cc index 788229cfd62..22ae28d29c3 100644 --- a/src/server/worker.cc +++ b/src/server/worker.cc @@ -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); }