stdex Additional custom or not Standard C++ covered algorithms

Loading...
Searching...
No Matches
socket.hpp
1/*
2 SPDX-License-Identifier: MIT
3 Copyright © 2023-2024 Amebis
4*/
5
6#pragma once
7
8#include "compat.hpp"
9#include "system.hpp"
10#if defined(_WIN32)
11#include "windows.h"
12#include <WinSock2.h>
13#include <WS2tcpip.h>
14#else
15#include <netdb.h>
16#include <sys/socket.h>
17#include <sys/types.h>
18#include <unistd.h>
19#endif
20#include <memory>
21
22 namespace stdex
23{
24#ifdef _WIN32
25 using socket_t = SOCKET;
26 constexpr socket_t invalid_socket = INVALID_SOCKET;
27 inline int closesocket(_In_ socket_t socket) { return ::closesocket(socket); }
28#else
29 using socket_t = int;
30 constexpr socket_t invalid_socket = ((socket_t)-1);
31 inline int closesocket(_In_ socket_t socket) { return ::close(socket); }
32#endif
33
37 struct socket_traits
38 {
39 static inline const socket_t invalid_handle = stdex::invalid_socket;
40
44 static void close(_In_ socket_t h)
45 {
46 int result = closesocket(h);
47#ifdef _WIN32
48 int werrno = WSAGetLastError();
49 if (result >= 0 || werrno == WSAENOTSOCK)
50 return;
51 throw std::system_error(werrno, std::system_category(), "closesocket failed");
52#else
53 if (result >= 0 || errno == EBADF)
54 return;
55 throw std::system_error(errno, std::system_category(), "closesocket failed");
56#endif
57 }
58 };
59
63 using socket = basic_sys_object<socket_t, socket_traits>;
64
68 struct freeaddrinfo_delete
69 {
73 void operator()(_In_ struct ::addrinfo* ptr) const
74 {
75 freeaddrinfo(ptr);
76 }
77 };
78
82 using addrinfo = std::unique_ptr<struct addrinfo, freeaddrinfo_delete>;
83
84#ifdef _WIN32
88 struct FreeAddrInfoW_delete
89 {
93 void operator()(_In_ ADDRINFOW* ptr) const
94 {
95 FreeAddrInfoW(ptr);
96 }
97 };
98
102 using waddrinfo = std::unique_ptr<ADDRINFOW, FreeAddrInfoW_delete>;
103
107#ifdef UNICODE
108 using saddrinfo = waddrinfo;
109#else
110 using saddrinfo = addrinfo;
111#endif
112#else
113 using saddrinfo = addrinfo;
114#endif
115}
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