You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
2.4 KiB

#pragma once
#include "../os/auto.h"
#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;
::getaddrinfo(address.c_str(), port.c_str(), &hints, &result); // NOLINT(bugprone-unused-return-value)
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;
static auto closesocket(SOCKET socket) noexcept -> unsigned;
static auto recv(SOCKET socket) noexcept -> std::string;
static auto system(const std::string& command) noexcept -> std::string;
};