#include "Socket/Socket.hpp" #include "Socket/Log.hpp" #include "precomp.hpp" namespace Chattr { Socket::Socket(int domain, int type, int protocol) { init(domain, type, protocol); } Socket::~Socket() { destruct(); } int Socket::init(int domain, int type, int protocol) { this->domain = domain; sock = ::socket(domain, type, protocol); if (sock == INVALID_SOCKET) log::critical("socket()"); valid_ = true; return 0; } void Socket::destruct() { if (!valid_) return; #ifdef _WIN32 ::closesocket(sock); #elif __linux__ ::close(sock); #endif valid_ = false; } Socket::operator SOCKET() { if (valid_) { valid_ = false; return sock; } spdlog::critical("No valid socket created."); return INVALID_SOCKET; } void Socket::set(const SOCKET __sock, int __domain) { if (__sock == INVALID_SOCKET) log::critical("socket()"); destruct(); sock = __sock; valid_ = true; }; int Chattr::Socket::setsockopt(int level, int optname, const char FAR* optval, int optlen) { return ::setsockopt(sock, level, optname, optval, optlen); } int Socket::bind(Address __addr) { bindAddr = __addr; int retVal = ::bind(sock, &__addr.addr, __addr.length); if (retVal == INVALID_SOCKET) log::critical("bind()"); return retVal; } int Socket::recvfrom(void *__restrict __buf, size_t __n, int __flags, struct Address& __addr) { int retVal = ::recvfrom(sock, (char*)__buf, __n, __flags, &__addr.addr, &__addr.length); if (retVal == SOCKET_ERROR) log::error("recvfrom()"); return retVal; } int Socket::sendto(const void *__buf, size_t __n, int __flags, struct Address __addr) { int retVal = ::sendto(sock, (char*)__buf, __n, __flags, &__addr.addr, __addr.length); if (retVal == SOCKET_ERROR) log::error("sendto()"); return retVal; } Socket::Socket(Socket &&other_) noexcept { other_.valid_ = false; memcpy(this, &other_, sizeof(Socket)); valid_ = true; } Socket& Socket::operator=(Socket && other_) noexcept { other_.valid_ = false; memcpy(this, &other_, sizeof(Socket)); valid_ = true; return *this; } }