Select Git revision
SchemeModule.cpp
Socket.cpp 6.02 KiB
#include <utils/Exceptions.hpp>
#include <utils/Socket.hpp>
#include <utils/Messenger.hpp>
#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <stdexcept>
#include <sys/socket.h>
#include <unistd.h>
class Socket::Internals
{
private:
int m_socket_fd;
sockaddr_in m_address;
const bool m_is_server_socket;
public:
friend Socket createServerSocket(int port_number);
friend Socket acceptClientSocket(const Socket& server);
friend Socket connectServerSocket(const std::string& server_name, int port_number);
friend std::ostream&
operator<<(std::ostream& os, const Socket::Internals& internals)
{
// This function's coverage is not performed since it's quite
// complex to create its various conditions
//
// LCOV_EXCL_START
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
if (::getnameinfo(reinterpret_cast<const sockaddr*>(&internals.m_address), sizeof(internals.m_address), hbuf,
sizeof(hbuf), sbuf, sizeof(sbuf), NI_NAMEREQD) == 0) {
os << hbuf << ':' << sbuf;
} else if (::getnameinfo(reinterpret_cast<const sockaddr*>(&internals.m_address), sizeof(internals.m_address), hbuf,
sizeof(hbuf), sbuf, sizeof(sbuf), NI_NUMERICHOST) == 0) {
if (std ::string{hbuf} == "0.0.0.0") {
if (::gethostname(hbuf, NI_MAXHOST) == 0) {
os << hbuf << ':' << sbuf;
} else {
os << "localhost:" << sbuf;
}
} else {
os << hbuf << ':' << sbuf;
}
} else {
os << "<unknown host>";
}
// LCOV_EXCL_STOP
return os;
}
bool
isServerSocket() const
{
return m_is_server_socket;
}
int
portNumber() const
{
return ntohs(m_address.sin_port);
}
int
fileDescriptor() const