ClientServerProject/modernize/sockets.h

60 lines
2.4 KiB
C
Raw Normal View History

2021-02-09 23:02:05 -05:00
#pragma once
2021-02-10 23:25:56 -05:00
#include "../os/auto.h"
2021-02-09 23:02:05 -05:00
#include <cstring>
#include <functional>
#include <iostream>
#include <memory>
#include <queue>
#include <string>
#include <unordered_map>
typedef std::uint16_t port;
inline port operator "" _p(const unsigned long long value) { return static_cast<port>(value); }
struct addrinfo_up_deleter { void operator()(addrinfo* ptr) const { ::freeaddrinfo(ptr); } };
typedef std::unique_ptr<addrinfo, addrinfo_up_deleter> addrinfo_up; /* Modern C++ shared pointer for addrinfo. */
struct popen_up_deleter { void operator()(FILE* ptr) const { pclose(ptr); } };
typedef std::unique_ptr<FILE, popen_up_deleter> popen_up; /* Modern C++ shared pointer for popen. */
class net
{
// ReSharper disable once CppInconsistentNaming
static std::unordered_map<SOCKET, std::queue<std::string>> message_queue;
public:
/* inlined functions*/
static auto bind(SOCKET socket, const addrinfo_up& address) noexcept -> int
{
return ::bind(socket, address->ai_addr, address->ai_addrlen);
}
static auto connect(SOCKET socket, const addrinfo_up& address) noexcept -> int
{
return ::connect(socket, address->ai_addr, address->ai_addrlen);
}
static auto getaddrinfo(const std::string& address, const std::string& port) noexcept -> addrinfo_up
{
addrinfo* result{};
addrinfo hints{};
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
2021-02-11 02:40:29 -05:00
::getaddrinfo(address.c_str(), port.c_str(), &hints, &result); // NOLINT(bugprone-unused-return-value)
2021-02-09 23:02:05 -05:00
return addrinfo_up(result);
}
static auto listen(const SOCKET socket) noexcept -> int { return ::listen(socket, SOMAXCONN); }
static auto send(SOCKET socket, const std::string& message) noexcept -> unsigned
{
return ::send(socket, message.c_str(), static_cast<int>(message.length() + 1u), MSG_NOSIGNAL); //make sure to include null terminator, this is our delim.
}
static auto socket(int af, int type, int protocol) noexcept -> SOCKET { return ::socket(af, type, protocol); }
/* extern functions */
static void prologue() noexcept;
static void epilogue() noexcept;
2021-02-11 02:40:29 -05:00
static auto closesocket(SOCKET socket) noexcept -> unsigned;
2021-02-09 23:02:05 -05:00
static auto recv(SOCKET socket) noexcept -> std::string;
static auto system(const std::string& command) noexcept -> std::string;
};