Skip to content
Snippets Groups Projects
Commit deb5c4ee authored by Benny Baumann's avatar Benny Baumann
Browse files

add: Allow conversion of socketaddress into its string representaton

parent 1986bdcf
No related branches found
No related tags found
1 merge request!1First unit tests
#pragma once #pragma once
#include <arpa/inet.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/un.h> #include <sys/un.h>
...@@ -9,6 +11,8 @@ ...@@ -9,6 +11,8 @@
#include <netinet/ip6.h> #include <netinet/ip6.h>
#include <functional> #include <functional>
#include <string>
#include <sstream>
#include "macros.hpp" #include "macros.hpp"
#include "net/netio_exception.hpp" #include "net/netio_exception.hpp"
...@@ -136,6 +140,42 @@ COMPILER_RESTORE("-Weffc++"); ...@@ -136,6 +140,42 @@ COMPILER_RESTORE("-Weffc++");
socklen_t size() const { socklen_t size() const {
return len; return len;
} }
std::string str() const {
std::ostringstream oss;
oss << "SocketAddress: ";
const int buffer_size = 1024;
char buffer[buffer_size];
switch (this->family()) {
case AF_INET:
inet_ntop(AF_INET, &((sockaddr_in*)&addr)->sin_addr, buffer, buffer_size);
oss << "IPv4 " << buffer << ":" << ntohs(((sockaddr_in*)&addr)->sin_port);
break;
case AF_INET6:
inet_ntop(AF_INET6, &((sockaddr_in6*)&addr)->sin6_addr, buffer, buffer_size);
oss << "IPv6 ["<< buffer << "]:" << ntohs(((sockaddr_in6*)&addr)->sin6_port);
break;
case AF_UNIX:
oss << "FileSocket " << ((sockaddr_un*)&addr)->sun_path;
break;
case AF_NETLINK: {
const auto nl_sock_ptr = (sockaddr_nl*) &addr;
oss << "Netlink g:" << nl_sock_ptr->nl_groups << " p:" << nl_sock_ptr->nl_pad << " pid:" << nl_sock_ptr->nl_pid;
break;
}
default:
oss << "Unknown Socket Address Type";
break;
}
return oss.str();
}
}; };
static inline std::ostream& operator<<(std::ostream& os, const socketaddr& sockaddr) {
return os << sockaddr.str();
}
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment