Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
Socket.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "../Foundation/AlignedStorage.h"
5#include "../Foundation/Result.h"
6#include "../Foundation/StringSpan.h"
7#include "../Foundation/UniqueHandle.h"
8#include "../Time/Time.h"
9
10namespace SC
11{
14
15namespace detail
16{
17
19#if SC_PLATFORM_WINDOWS
20
21struct SocketDescriptorDefinition
22{
23 using Handle = size_t; // SOCKET
24 static Result releaseHandle(Handle& handle);
25
26 static constexpr Handle Invalid = ~static_cast<Handle>(0); // INVALID_SOCKET
27};
28
29#else
30
31struct SocketDescriptorDefinition
32{
33 using Handle = int; // fd
34 static Result releaseHandle(Handle& handle);
35
36 static constexpr Handle Invalid = -1; // invalid fd
37};
38
39#endif
40} // namespace detail
41
44{
51
58
65
72
79
87
88 private:
89 friend struct SocketDescriptor;
90 friend struct SocketIPAddressInternal;
91 [[nodiscard]] static AddressFamily AddressFamilyFromInt(int value);
92 [[nodiscard]] static unsigned char toNative(AddressFamily family);
93 [[nodiscard]] static SocketType SocketTypeFromInt(int value);
94 [[nodiscard]] static int toNative(SocketType family);
95
96 [[nodiscard]] static ProtocolType ProtocolTypeFromInt(int value);
97 [[nodiscard]] static int toNative(ProtocolType family);
98};
99
105{
107 static constexpr int MAX_ASCII_STRING_LENGTH = 46;
108
111
115
119
122 [[nodiscard]] uint16_t getPort() const;
123
128 [[nodiscard]] Result fromAddressPort(StringSpan interfaceAddress, uint16_t port);
129
131 [[nodiscard]] uint32_t sizeOfHandle() const;
132
134 [[nodiscard]] bool isValid() const;
135
140 template <size_t N>
141 [[nodiscard]] StringSpan toString(char (&buffer)[N]) const
142 {
143 static_assert(N >= MAX_ASCII_STRING_LENGTH, "Insufficient buffer");
144 return formatAddress(buffer);
145 }
146
149
150 private:
151 [[nodiscard]] StringSpan formatAddress(Span<char> buffer) const;
152 friend struct SocketServer;
153 friend struct SocketClient;
154
155 struct Internal;
156};
157
163struct SC_COMPILER_EXPORT SocketDescriptor : public UniqueHandle<detail::SocketDescriptorDefinition>
164{
172 [[nodiscard]] Result create(SocketFlags::AddressFamily addressFamily,
173 SocketFlags::SocketType socketType = SocketFlags::SocketStream,
174 SocketFlags::ProtocolType protocol = SocketFlags::ProtocolTcp,
175 SocketFlags::BlockingType blocking = SocketFlags::Blocking,
176 SocketFlags::InheritableType inheritable = SocketFlags::NonInheritable);
177
181 Result isInheritable(bool& value) const;
182
187
191 Result setBlocking(bool value);
192
197
202};
203
209{
212 SocketServer(SocketDescriptor& socket) : socket(socket) {}
213
216 [[nodiscard]] Result close();
217
221 [[nodiscard]] Result bind(SocketIPAddress nativeAddress);
222
227 [[nodiscard]] Result listen(uint32_t numberOfWaitingConnections);
228
233 [[nodiscard]] Result accept(SocketFlags::AddressFamily addressFamily, SocketDescriptor& newClient);
234
235 private:
236 SocketDescriptor& socket;
237};
238
250{
253 SocketClient(const SocketDescriptor& socket) : socket(socket) {}
254
260 [[nodiscard]] Result connect(StringSpan address, uint16_t port);
261
265 [[nodiscard]] Result connect(SocketIPAddress ipAddress);
266
270 [[nodiscard]] Result write(Span<const char> data);
271
276 [[nodiscard]] Result read(Span<char> data, Span<char>& readData);
277
283 [[nodiscard]] Result readWithTimeout(Span<char> data, Span<char>& readData, Time::Milliseconds timeout);
284
285 private:
286 const SocketDescriptor& socket;
287};
288
294{
302 [[nodiscard]] static Result resolveDNS(StringSpan host, Span<char>& ipAddress);
303};
304
307{
310 [[nodiscard]] static Result initNetworking();
311
314 [[nodiscard]] static Result shutdownNetworking();
315
318 [[nodiscard]] static bool isNetworkingInited();
319
320 private:
321 struct Internal;
322};
323
325} // namespace SC
#define SC_COMPILER_EXPORT
Macro for symbol visibility in non-MSVC compilers.
Definition Compiler.h:78
unsigned short uint16_t
Platform independent (2) bytes unsigned int.
Definition PrimitiveTypes.h:37
unsigned long size_t
Platform independent unsigned size type.
Definition PrimitiveTypes.h:56
unsigned int uint32_t
Platform independent (4) bytes unsigned int.
Definition PrimitiveTypes.h:38
A buffer of bytes with given alignment.
Definition AlignedStorage.h:29
An ascii string used as boolean result. SC_TRY macro forwards errors to caller.
Definition Result.h:12
Use a SocketDescriptor as a client (example a TCP or UDP socket client).
Definition Socket.h:250
Result read(Span< char > data, Span< char > &readData)
Read bytes from this socket blocking until they're actually received.
Result readWithTimeout(Span< char > data, Span< char > &readData, Time::Milliseconds timeout)
Read bytes from this socket blocking until they're actually received or timeout occurs.
SocketClient(const SocketDescriptor &socket)
Constructs this SocketClient from a SocketDescriptor (already created with SocketDescriptor::create)
Definition Socket.h:253
Result connect(StringSpan address, uint16_t port)
Connect to a given address and port combination.
Result connect(SocketIPAddress ipAddress)
Connect to a given address and port combination.
Result write(Span< const char > data)
Writes bytes to this socket.
Synchronous DNS Resolution.
Definition Socket.h:294
static Result resolveDNS(StringSpan host, Span< char > &ipAddress)
Resolve an host string to an ip address (blocking until DNS response arrives)
Low-level OS socket handle.
Definition Socket.h:164
Result shutdown(SocketFlags::ShutdownType shutdownType)
Shuts down the socket for reading, writing, or both.
Result isInheritable(bool &value) const
Check if socket is inheritable by child processes.
Result setBlocking(bool value)
Changes the blocking flag for this socket (if IO reads / writes should be blocking or not)
Result setInheritable(bool value)
Changes the inheritable flag for this socket.
Result create(SocketFlags::AddressFamily addressFamily, SocketFlags::SocketType socketType=SocketFlags::SocketStream, SocketFlags::ProtocolType protocol=SocketFlags::ProtocolTcp, SocketFlags::BlockingType blocking=SocketFlags::Blocking, SocketFlags::InheritableType inheritable=SocketFlags::NonInheritable)
Creates a new SocketDescriptor Descriptor of given family, type, protocol.
Result getAddressFamily(SocketFlags::AddressFamily &addressFamily) const
Get address family (IPV4 / IPV6) of this socket.
Flags for SocketDescriptor (Blocking / Inheritable, IPVx, SocketType)
Definition Socket.h:44
SocketType
Sets the socket type, if it's a Datagram (for UDP) or Streaming (for TCP and others)
Definition Socket.h:68
@ SocketStream
Sets the socket type as Streaming type (for TCP and others)
Definition Socket.h:69
@ SocketDgram
Sets the socket type as Streaming type (for UDP)
Definition Socket.h:70
AddressFamily
Sets the address family of an IP Address (IPv4 or IPV6)
Definition Socket.h:61
@ AddressFamilyIPV6
IP Address is IPV6.
Definition Socket.h:63
@ AddressFamilyIPV4
IP Address is IPV4.
Definition Socket.h:62
InheritableType
Sets the socket inheritable behaviour for child processes.
Definition Socket.h:54
@ NonInheritable
SocketDescriptor will not be inherited by child processes.
Definition Socket.h:55
@ Inheritable
SocketDescriptor will be inherited by child processes.
Definition Socket.h:56
ShutdownType
Sets the type of shutdown to perform.
Definition Socket.h:82
@ ShutdownBoth
Shuts down the socket for both reading and writing.
Definition Socket.h:85
@ ShutdownWrite
Shuts down the socket for writing.
Definition Socket.h:84
@ ShutdownRead
Shuts down the socket for reading.
Definition Socket.h:83
BlockingType
Sets the socket as blocking / nonblocking mode.
Definition Socket.h:47
@ NonBlocking
SocketDescriptor is in non-blocking mode.
Definition Socket.h:48
@ Blocking
SocketDescriptor is in blocking mode.
Definition Socket.h:49
ProtocolType
Sets the socket protocol type.
Definition Socket.h:75
@ ProtocolUdp
The protocol is UDP.
Definition Socket.h:77
@ ProtocolTcp
The protocol is TCP.
Definition Socket.h:76
Native representation of an IP Address.
Definition Socket.h:105
uint16_t getPort() const
Get port of this ip address.
char[MAX_ASCII_STRING_LENGTH] AsciiBuffer
Buffer for storing the ASCII representation of an IP Address.
Definition Socket.h:110
AlignedStorage< 28 > handle
Handle to native OS representation of the IP Address.
Definition Socket.h:148
static constexpr int MAX_ASCII_STRING_LENGTH
Maximum length of the ASCII representation of an IP Address.
Definition Socket.h:107
Result fromAddressPort(StringSpan interfaceAddress, uint16_t port)
Builds this SocketIPAddress parsing given address string and port.
StringSpan toString(char(&buffer)[N]) const
Returns the text representation of this SocketIPAddress.
Definition Socket.h:141
SocketFlags::AddressFamily getAddressFamily() const
Get Address family of this ip address (IPV4 or IPV6)
uint32_t sizeOfHandle() const
Size of the native IP Address representation.
SocketIPAddress(SocketFlags::AddressFamily addressFamily=SocketFlags::AddressFamilyIPV4)
Constructs an ip address from a given family (IPV4 or IPV6)
bool isValid() const
Checks if this is a valid IPV4 or IPV6 address.
Networking globals initialization (Winsock2 WSAStartup)
Definition Socket.h:307
static Result shutdownNetworking()
Shutdowns Winsock2 on Windows (WSAStartup)
static bool isNetworkingInited()
Check if initNetworking has been previously called.
static Result initNetworking()
Initializes Winsock2 on Windows (WSAStartup)
Use a SocketDescriptor as a Server (example TCP or UDP Socket Server).
Definition Socket.h:209
Result listen(uint32_t numberOfWaitingConnections)
Start listening for incoming connections at a specific address / port combination (after bind)
SocketServer(SocketDescriptor &socket)
Build a SocketServer from a SocketDescriptor (already created with SocketDescriptor::create)
Definition Socket.h:212
Result close()
Calls SocketDescriptor::close.
Result bind(SocketIPAddress nativeAddress)
Binds this socket to a given address / port combination.
Result accept(SocketFlags::AddressFamily addressFamily, SocketDescriptor &newClient)
Accepts a new client, blocking while waiting for it.
View over a contiguous sequence of items (pointer + size in elements).
Definition Span.h:29
An read-only view over a string (to avoid including Strings library when parsing is not needed).
Definition StringSpan.h:31
Type-safe wrapper of uint64 used to represent milliseconds.
Definition Time.h:44
Move only handle that has a special tag value flagging its invalid state.
Definition UniqueHandle.h:67