mirror of
https://github.com/savoirfairelinux/opendht.git
synced 2026-11-08 12:28:42 +00:00
sockaddr: add fmt formatter
This commit is contained in:
1 parent
6cfede0868
commit
6919df592f
2 files changed
+24
-5
No files matched your search
@@ -20,6 +20,10 @@
|
||||
|
||||
#include "def.h"
|
||||
|
||||
#include <fmt/core.h>
|
||||
#include <fmt/format.h>
|
||||
#include <fmt/ostream.h>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
@@ -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<sockaddr, free_delete> addr {};
|
||||
@@ -309,3 +319,7 @@ private:
|
||||
OPENDHT_PUBLIC bool operator==(const SockAddr& a, const SockAddr& b);
|
||||
|
||||
}
|
||||
|
||||
#if FMT_VERSION >= 90000
|
||||
template <> struct fmt::formatter<dht::SockAddr> : ostream_formatter {};
|
||||
#endif
|
||||
+10
-5
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user