107 lines
2.2 KiB
C++
107 lines
2.2 KiB
C++
#include "Socket/Socket.hpp"
|
|
#include "Socket/Log.hpp"
|
|
#include "precomp.hpp"
|
|
|
|
namespace Chattr {
|
|
|
|
Socket::Socket() {
|
|
#ifdef _WIN32
|
|
WSADATA wsa;
|
|
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
|
|
log::critical("WSAStartup()");
|
|
#endif
|
|
}
|
|
|
|
Socket::Socket(int domain, int type, int protocol) {
|
|
#ifdef _WIN32
|
|
WSADATA wsa;
|
|
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
|
|
log::critical("WSAStartup()");
|
|
#endif
|
|
init(domain, type, protocol);
|
|
}
|
|
|
|
Socket::~Socket() {
|
|
if (!valid_)
|
|
return;
|
|
#ifdef _WIN32
|
|
closesocket(sock_);
|
|
WSACleanup();
|
|
#elif __linux__
|
|
::close(sock_);
|
|
#endif
|
|
}
|
|
|
|
void Socket::init(int domain, int type, int protocol) {
|
|
if (domain == AF_INET)
|
|
bindAddr.length = sizeof(sockaddr_in);
|
|
else if (domain == AF_INET6)
|
|
bindAddr.length = sizeof(sockaddr_in6);
|
|
|
|
sock_ = ::socket(domain, type, protocol);
|
|
if (sock_ == INVALID_SOCKET)
|
|
log::critical("socket()");
|
|
|
|
valid_ = true;
|
|
}
|
|
|
|
Socket::operator SOCKET() const {
|
|
if (valid_)
|
|
return sock_;
|
|
spdlog::critical("No valid socket created.");
|
|
return INVALID_SOCKET;
|
|
}
|
|
|
|
void Socket::move(const SOCKET __sock) {
|
|
if (__sock == INVALID_SOCKET)
|
|
log::critical("socket()");
|
|
|
|
if (valid_) {
|
|
#ifdef _WIN32
|
|
closesocket(sock_);
|
|
WSACleanup();
|
|
#elif __linux__
|
|
::close(sock_);
|
|
#endif
|
|
}
|
|
else {
|
|
#ifdef _WIN32
|
|
WSADATA wsa;
|
|
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
|
|
log::critical("WSAStartup()");
|
|
#endif
|
|
}
|
|
|
|
sock_ = __sock;
|
|
valid_ = true;
|
|
};
|
|
|
|
void Socket::bind(sockaddr *__addr) {
|
|
bind((struct sockaddr *)__addr, sizeof(sockaddr));
|
|
}
|
|
|
|
void Socket::bind(sockaddr *__addr, socklen_t __len) {
|
|
bindAddr.length = __len;
|
|
std::memcpy(&bindAddr, __addr, __len);
|
|
int retVal = ::bind(sock_, __addr, __len);
|
|
if (retVal == INVALID_SOCKET)
|
|
log::critical("bind()");
|
|
}
|
|
|
|
void Socket::bind(sockaddr_in *__addr) {
|
|
bind((struct sockaddr *)__addr, sizeof(sockaddr_in));
|
|
}
|
|
|
|
void Socket::bind(sockaddr_in *__addr, socklen_t __len) {
|
|
bind((struct sockaddr *)__addr, __len);
|
|
}
|
|
|
|
void Socket::bind(sockaddr_in6 *__addr) {
|
|
bind((struct sockaddr *)__addr, sizeof(sockaddr_in6));
|
|
}
|
|
|
|
void Socket::bind(sockaddr_in6 *__addr, socklen_t __len) {
|
|
bind((struct sockaddr *)__addr, __len);
|
|
}
|
|
|
|
} |