diff --git a/include/opendht/sockaddr.h b/include/opendht/sockaddr.h index 717515cd..b2e84686 100644 --- a/include/opendht/sockaddr.h +++ b/include/opendht/sockaddr.h @@ -20,6 +20,10 @@ #include "def.h" +#include +#include +#include + #ifndef _WIN32 #include #include @@ -48,6 +52,7 @@ typedef uint16_t in_port_t; namespace dht { +OPENDHT_PUBLIC void print_addr(std::ostream& os, const sockaddr* sa, socklen_t slen); OPENDHT_PUBLIC std::string print_addr(const sockaddr* sa, socklen_t slen); OPENDHT_PUBLIC std::string print_addr(const sockaddr_storage& ss, socklen_t sslen); @@ -289,6 +294,11 @@ public: (uint8_t*)b.get()+start, len) < 0; } }; + OPENDHT_PUBLIC friend std::ostream& operator<< (std::ostream& s, const SockAddr& h) { + print_addr(s, h.get(), h.getLength()); + return s; + } + private: struct free_delete { void operator()(void* p) { ::free(p); } }; std::unique_ptr addr {}; @@ -309,3 +319,7 @@ private: OPENDHT_PUBLIC bool operator==(const SockAddr& a, const SockAddr& b); } + +#if FMT_VERSION >= 90000 +template <> struct fmt::formatter : ostream_formatter {}; +#endif \ No newline at end of file diff --git a/src/utils.cpp b/src/utils.cpp index 9bb945bd..046830ff 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -103,21 +103,26 @@ SockAddr::setAddress(const char* address) throw std::runtime_error(std::string("Can't parse IP address: ") + strerror(errno)); } -std::string -print_addr(const sockaddr* sa, socklen_t slen) +void print_addr(std::ostream& out, const sockaddr* sa, socklen_t slen) { char hbuf[NI_MAXHOST]; char sbuf[NI_MAXSERV]; - std::ostringstream out; if (sa and slen and !getnameinfo(sa, slen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) { if (sa->sa_family == AF_INET6) - out << "[" << hbuf << "]"; + out << '[' << hbuf << ']'; else out << hbuf; if (std::strcmp(sbuf, "0")) - out << ":" << sbuf; + out << ':' << sbuf; } else out << "[invalid address]"; +} + +std::string +print_addr(const sockaddr* sa, socklen_t slen) +{ + std::ostringstream out; + print_addr(out, sa, slen); return out.str(); }