Add format_address

This commit is contained in:
Théophile Bastian 2020-06-05 16:15:20 +02:00
parent a497dade2e
commit c728aacb70
2 changed files with 57 additions and 0 deletions

View file

@ -1,6 +1,7 @@
#include <cstdio>
#include <string.h>
#include <stdarg.h>
#include <arpa/inet.h>
#include "util.hpp"
@ -17,6 +18,41 @@ void do_debugf(int level, const char *format, ...)
va_end(args);
}
const char *
format_address(const unsigned char *address)
{
static char buf[4][INET6_ADDRSTRLEN];
static int i = 0;
i = (i + 1) % 4;
/*
if(v4mapped(address))
inet_ntop(AF_INET, address + 12, buf[i], INET6_ADDRSTRLEN);
else
*/
inet_ntop(AF_INET6, address, buf[i], INET6_ADDRSTRLEN);
return buf[i];
}
namespace std {
size_t hash<in6_addr>::operator() (const in6_addr& addr) const {
size_t out_hash = 0;
for(int i=0; i < 4; ++i) {
uint32_t value;
memcpy((unsigned char*)(&value),
addr.s6_addr + 4*i,
4);
out_hash ^= (std::hash<uint32_t>{}(value) << 1);
}
return out_hash;
}
bool equal_to<in6_addr>::operator()(
const in6_addr& lhs, const in6_addr& rhs) const
{
return memcmp(lhs.s6_addr, rhs.s6_addr, sizeof(lhs.s6_addr)) == 0;
}
}
MsgException::MsgException(const std::string& msg, int code, bool is_perror)
: _msg(msg), _code(code)
{

View file

@ -2,6 +2,7 @@
#include <exception>
#include <string>
#include <netinet/in.h>
/* Debugging -- taken from babeld */
@ -43,6 +44,26 @@ static inline void kdebugf(const char *format, ...) { return; }
void do_debugf(int level, const char *format, ...);
/** format_address -- taken from babeld */
const char* format_address(const unsigned char* address);
/** in6_addr hash & equality */
namespace std {
template<>
class hash<in6_addr> {
public:
size_t operator()(const in6_addr& addr) const;
};
template<>
class equal_to<in6_addr> {
public:
bool operator()(const in6_addr& lhs, const in6_addr& rhs) const;
};
}
/** MsgException -- an exception bearing a passed explanation message
*