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#else
14#include <sys/socket.h>
15#include <unistd.h>
16#endif
17
18namespace stdex
19{
20#ifdef _WIN32
21 using socket_t = SOCKET;
22 constexpr socket_t invalid_socket = INVALID_SOCKET;
23 inline int closesocket(_In_ socket_t socket) { return ::closesocket(socket); }
24#else
25 using socket_t = int;
26 constexpr socket_t invalid_socket = ((socket_t)-1);
27 inline int closesocket(_In_ socket_t socket) { return ::close(socket); }
28#endif
29
34 {
35 static inline const socket_t invalid_handle = stdex::invalid_socket;
36
40 static void close(_In_ socket_t h)
41 {
42 int result = closesocket(h);
43#ifdef _WIN32
44 int werrno = WSAGetLastError();
45 if (result >= 0 || werrno == WSAENOTSOCK)
46 return;
47 throw std::system_error(werrno, std::system_category(), "closesocket failed");
48#else
49 if (result >= 0 || errno == EBADF)
50 return;
51 throw std::system_error(errno, std::system_category(), "closesocket failed");
52#endif
53 }
54 };
55
59 using socket = basic_sys_object<socket_t, socket_traits>;
60}
Socket operations.
Definition socket.hpp:34
static void close(socket_t h)
Closes socket.
Definition socket.hpp:40