# stdex: include/stdex/socket.hpp Source File

Loading...
Searching...
No Matches
socket.hpp
/*
SPDX-License-Identifier: MIT
Copyright © 2023-2024 Amebis
*/
#pragma once
#include "compat.hpp"
#include "system.hpp"
#if defined(_WIN32)
#include "windows.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#else
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include <memory>
namespace stdex
{
#ifdef _WIN32
using socket_t = SOCKET;
constexpr socket_t invalid_socket = INVALID_SOCKET;
inline int closesocket(_In_ socket_t socket) { return ::closesocket(socket); }
#else
using socket_t = int;
constexpr socket_t invalid_socket = ((socket_t)-1);
inline int closesocket(_In_ socket_t socket) { return ::close(socket); }
#endif
struct socket_traits
{
static inline const socket_t invalid_handle = stdex::invalid_socket;
static void close(_In_ socket_t h)
{
int result = closesocket(h);
#ifdef _WIN32
int werrno = WSAGetLastError();
if (result >= 0 || werrno == WSAENOTSOCK)
return;
throw std::system_error(werrno, std::system_category(), "closesocket failed");
#else
if (result >= 0 || errno == EBADF)
return;
throw std::system_error(errno, std::system_category(), "closesocket failed");
#endif
}
};
using socket = basic_sys_object<socket_t, socket_traits>;
struct freeaddrinfo_delete
{
void operator()(_In_ struct ::addrinfo* ptr) const
{
freeaddrinfo(ptr);
}
};
using addrinfo = std::unique_ptr<struct addrinfo, freeaddrinfo_delete>;
#ifdef _WIN32
struct FreeAddrInfoW_delete
{
void operator()(_In_ ADDRINFOW* ptr) const
{
FreeAddrInfoW(ptr);
}
};
using waddrinfo = std::unique_ptr<ADDRINFOW, FreeAddrInfoW_delete>;
#ifdef UNICODE
using saddrinfo = waddrinfo;
#else
using saddrinfo = addrinfo;
#endif
#else
using saddrinfo = addrinfo;
#endif
}
stdex::freeaddrinfo_delete
Deleter for unique_ptr using freeaddrinfo.
Definition socket.hpp:69
stdex::freeaddrinfo_delete::operator()
void operator()(struct ::addrinfo *ptr) const
Delete a pointer.
Definition socket.hpp:73
stdex::socket_traits
Socket operations.
Definition socket.hpp:38
stdex::socket_traits::close
static void close(socket_t h)
Closes socket.
Definition socket.hpp:44