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
9namespace SC
10{
13
14namespace detail
15{
16
18#if SC_PLATFORM_WINDOWS
19
20struct SocketDescriptorDefinition
21{
22 using Handle = size_t; // SOCKET
23 static Result releaseHandle(Handle& handle);
24
25 static constexpr Handle Invalid = ~static_cast<Handle>(0); // INVALID_SOCKET
26};
27
28#else
29
30struct SocketDescriptorDefinition
31{
32 using Handle = int; // fd
33 static Result releaseHandle(Handle& handle);
34
35 static constexpr Handle Invalid = -1; // invalid fd
36};
37
38#endif
39} // namespace detail
40
43{
50
57
64
71
78
86
87 private:
88 friend struct SocketDescriptor;
89 friend struct SocketIPAddressInternal;
90 [[nodiscard]] static AddressFamily AddressFamilyFromInt(int value);
91 [[nodiscard]] static unsigned char toNative(AddressFamily family);
92 [[nodiscard]] static SocketType SocketTypeFromInt(int value);
93 [[nodiscard]] static int toNative(SocketType family);
94
95 [[nodiscard]] static ProtocolType ProtocolTypeFromInt(int value);
96 [[nodiscard]] static int toNative(ProtocolType family);
97};
98
104{
106 static constexpr int MAX_ASCII_STRING_LENGTH = 46;
107
110
114
118
121 [[nodiscard]] uint16_t getPort() const;
122
127 [[nodiscard]] Result fromAddressPort(StringSpan interfaceAddress, uint16_t port);
128
130 [[nodiscard]] uint32_t sizeOfHandle() const;
131
133 [[nodiscard]] bool isValid() const;
134
139 template <size_t N>
140 [[nodiscard]] StringSpan toString(char (&buffer)[N]) const
141 {
142 static_assert(N >= MAX_ASCII_STRING_LENGTH, "Insufficient buffer");
143 return formatAddress(buffer);
144 }
145
148
149 private:
150 [[nodiscard]] StringSpan formatAddress(Span<char> buffer) const;
151 friend struct SocketServer;
152 friend struct SocketClient;
153
154 struct Internal;
155};
156
162struct SC_COMPILER_EXPORT SocketDescriptor : public UniqueHandle<detail::SocketDescriptorDefinition>
163{
171 [[nodiscard]] Result create(SocketFlags::AddressFamily addressFamily,
172 SocketFlags::SocketType socketType = SocketFlags::SocketStream,
173 SocketFlags::ProtocolType protocol = SocketFlags::ProtocolTcp,
174 SocketFlags::BlockingType blocking = SocketFlags::Blocking,
175 SocketFlags::InheritableType inheritable = SocketFlags::NonInheritable);
176
180 Result isInheritable(bool& value) const;
181
186
190 Result setBlocking(bool value);
191
196
201};
202
208{
211 SocketServer(SocketDescriptor& socket) : socket(socket) {}
212
215 [[nodiscard]] Result close();
216
220 [[nodiscard]] Result bind(SocketIPAddress nativeAddress);
221
226 [[nodiscard]] Result listen(uint32_t numberOfWaitingConnections);
227
232 [[nodiscard]] Result accept(SocketFlags::AddressFamily addressFamily, SocketDescriptor& newClient);
233
234 private:
235 SocketDescriptor& socket;
236};
237
249{
252 SocketClient(const SocketDescriptor& socket) : socket(socket) {}
253
259 [[nodiscard]] Result connect(StringSpan address, uint16_t port);
260
264 [[nodiscard]] Result connect(SocketIPAddress ipAddress);
265
269 [[nodiscard]] Result write(Span<const char> data);
270
275 [[nodiscard]] Result read(Span<char> data, Span<char>& readData);
276
282 [[nodiscard]] Result readWithTimeout(Span<char> data, Span<char>& readData, int64_t timeout);
283
284 private:
285 const SocketDescriptor& socket;
286};
287
293{
301 [[nodiscard]] static Result resolveDNS(StringSpan host, Span<char>& ipAddress);
302};
303
306{
309 [[nodiscard]] static Result initNetworking();
310
313 [[nodiscard]] static Result shutdownNetworking();
314
317 [[nodiscard]] static bool isNetworkingInited();
318
319 private:
320 struct Internal;
321};
322
324} // namespace SC
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
long long int64_t
Platform independent (8) bytes signed int.
Definition PrimitiveTypes.h:50
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:249
Result read(Span< char > data, Span< char > &readData)
Read bytes from this socket blocking until they're actually received.
SocketClient(const SocketDescriptor &socket)
Constructs this SocketClient from a SocketDescriptor (already created with SocketDescriptor::create)
Definition Socket.h:252
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 readWithTimeout(Span< char > data, Span< char > &readData, int64_t timeout)
Read bytes from this socket blocking until they're actually received or timeout occurs.
Result write(Span< const char > data)
Writes bytes to this socket.
Synchronous DNS Resolution.
Definition Socket.h:293
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:163
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:43
SocketType
Sets the socket type, if it's a Datagram (for UDP) or Streaming (for TCP and others)
Definition Socket.h:67
@ SocketStream
Sets the socket type as Streaming type (for TCP and others)
Definition Socket.h:68
@ SocketDgram
Sets the socket type as Streaming type (for UDP)
Definition Socket.h:69
AddressFamily
Sets the address family of an IP Address (IPv4 or IPV6)
Definition Socket.h:60
@ AddressFamilyIPV6
IP Address is IPV6.
Definition Socket.h:62
@ AddressFamilyIPV4
IP Address is IPV4.
Definition Socket.h:61
InheritableType
Sets the socket inheritable behaviour for child processes.
Definition Socket.h:53
@ NonInheritable
SocketDescriptor will not be inherited by child processes.
Definition Socket.h:54
@ Inheritable
SocketDescriptor will be inherited by child processes.
Definition Socket.h:55
ShutdownType
Sets the type of shutdown to perform.
Definition Socket.h:81
@ ShutdownBoth
Shuts down the socket for both reading and writing.
Definition Socket.h:84
@ ShutdownWrite
Shuts down the socket for writing.
Definition Socket.h:83
@ ShutdownRead
Shuts down the socket for reading.
Definition Socket.h:82
BlockingType
Sets the socket as blocking / nonblocking mode.
Definition Socket.h:46
@ NonBlocking
SocketDescriptor is in non-blocking mode.
Definition Socket.h:47
@ Blocking
SocketDescriptor is in blocking mode.
Definition Socket.h:48
ProtocolType
Sets the socket protocol type.
Definition Socket.h:74
@ ProtocolUdp
The protocol is UDP.
Definition Socket.h:76
@ ProtocolTcp
The protocol is TCP.
Definition Socket.h:75
Native representation of an IP Address.
Definition Socket.h:104
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:109
AlignedStorage< 28 > handle
Handle to native OS representation of the IP Address.
Definition Socket.h:147
static constexpr int MAX_ASCII_STRING_LENGTH
Maximum length of the ASCII representation of an IP Address.
Definition Socket.h:106
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:140
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:306
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:208
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:211
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:37
Move only handle that has a special tag value flagging its invalid state.
Definition UniqueHandle.h:27