xentara-utils v2.0.4
The Xentara Utility Library
Loading...
Searching...
No Matches
xentara::utils::network::Socket Class Referencefinal

A socket. More...

#include <xentara/utils/network/Socket.hpp>

Public Types

enum class  Direction { Read , Write , ReadWrite }
 Directions for sutdown(). More...
 

Public Member Functions

 Socket () noexcept=default
 Default constructor.
 
template<tools::OneOf< NonBlockingTag, Protocol >... Options>
 Socket (int addressFamily, int socketType, Options... options)
 Constructor that creates a socket.
 
 Socket (posix::File socketFileDescriptor) noexcept
 Conversion from a Posix file descriptor.
 
 Socket (windows::Socket socket) noexcept
 Conversion from a native socket.
 
 operator bool () const noexcept
 Checks whether the object contains a valid socket.
 
auto addressFamily () const noexcept -> int
 Gets the address family of the socket, also called the socket domain.
 
auto socketType () const noexcept -> int
 Gets the socket type.
 
auto protocol () const noexcept -> int
 Gets the protocol of the socket.
 
template<typename Value >
auto option (int level, int optionName) const -> Value
 Gets a socket option.
 
template<typename Value >
auto setOption (int level, int optionName, const Value &value) -> void
 Sets a socket option.
 
template<typename Value >
auto getOption (int level, int optionName, std::nothrow_t) const noexcept -> xentara::utils::eh::expected< Value, std::error_code >
 Gets a socket option.
 
template<typename Value >
auto setOption (int level, int optionName, const Value &value, std::nothrow_t) noexcept -> std::error_code
 Sets a socket option without throwing exceptions.
 
auto makeNonBlocking (bool nonBlocking=true) -> void
 Sets the non-blocking option of the socket.
 
auto connect (const Address &address) -> bool
 Connects to an address.
 
auto bind (PortNumber portNumber) -> void
 Binds the socket to a port number on all local interfaces.
 
auto bind (const Address &address) -> void
 Binds the socket to a specific address.
 
template<tools::OneOf< Backlog >... Options>
auto listen (Options... options) -> void
 Puts the socket into listening mode.
 
template<tools::OneOf< NonBlockingTag >... Options>
auto accept (Options... options) const -> Socket
 Accepts a connection from a socket in listening mode.
 
auto localAddress () const -> Address
 Gets the local address of a bound or connected socket.
 
auto remoteAddress () const -> Address
 Gets the address that the socket is connected to.
 
auto poll (short events, std::optional< std::chrono::nanoseconds > timeout=std::nullopt) const -> short
 Waits for events on the socket.
 
auto poll (short events, const io::StopSource &stopSource, std::optional< std::chrono::nanoseconds > timeout=std::nullopt) const -> short
 Waits for events on the socket using a stop source.
 
auto waitForEvent (short events, const io::StopSource &stopSource, std::optional< std::chrono::nanoseconds > timeout=std::nullopt) const -> short
 Waits for an event on the socket, using a timeout.
 
auto performOverlappedIo (functional::function_ref< auto(SOCKET, OVERLAPPED *) → BOOL > operation, HANDLE event, std::optional< std::chrono::nanoseconds > timeout=std::nullopt) -> std::optional< DWORD >
 Performs an overlapped I/O operation.
 
auto performOverlappedIo (functional::function_ref< auto(SOCKET, OVERLAPPED *) → BOOL > operation, std::span< HANDLE > waitObjects, std::optional< std::chrono::nanoseconds > timeout=std::nullopt) -> std::optional< windows::OverlappedResult >
 Performs an overlapped I/O operation.
 
auto send (const void *data, std::size_t size, int flags=0) const -> std::size_t
 Sends data to the socket.
 
auto receive (void *buffer, std::size_t size, int flags=0) const -> std::optional< std::size_t >
 Receive data from the socket.
 
auto sendTo (const void *data, std::size_t size, const Address &destination, int flags=0) const -> std::size_t
 Sends data to a specific destination over the socket.
 
auto receiveFrom (void *buffer, std::size_t size, int flags=0) const -> std::pair< std::optional< std::size_t >, Address >
 Receive data from the socket and returns the sender address.
 
auto error () const -> std::error_code
 Returns the error status, and clears it.
 
template<std::derived_from< std::system_error > Exception, typename... ExceptionArguments>
auto throwError (ExceptionArguments &&...exceptionArguments) -> void
 Throws an exception if the socket contains an error.
 
auto shutdown (Direction directions=Direction::ReadWrite) -> void
 Shuts down the socket.
 
auto close () noexcept -> void
 Closes the socket, if one is open.
 
auto native () const noexcept -> int
 Gets the underlying Posix file descriptor for the socket.
 
auto native () const noexcept -> SOCKET
 Gets the underlying Windows Sockets 2 SOCKET.
 
auto release () noexcept -> int
 Removes the the socket and passes ownership to the caller.
 
auto release () noexcept -> SOCKET
 Removes the socket and passes ownership to the caller.
 
auto description () const noexcept -> std::string_view
 Gets a description for the socket.
 

Static Public Member Functions

static auto poll (std::span< pollfd > sockets, std::optional< std::chrono::nanoseconds > timeout=std::nullopt) -> bool
 Waits for events on one or more sockets.
 
static auto poll (std::span< pollfd > sockets, const io::StopSource &stopSource, std::optional< std::chrono::nanoseconds > timeout=std::nullopt) -> bool
 Waits for events on one or more sockets using a stop source.
 
template<tools::OneOf< NonBlockingTag, Protocol >... Options>
static auto compatibleSocket (int socketType, const Address &address, Options... options) -> Socket
 Creates a socket that is compatible with an address.
 
template<tools::OneOf< NonBlockingTag, Protocol, Timeout, WithStopSource >... Options>
static auto connectedSocket (int socketType, const Address &address, Options... options) -> Socket
 Creates a socket that is connected to an address.
 
template<tools::OneOf< NonBlockingTag, Protocol, Timeout, WithStopSource >... Options>
static auto connectedSocket (int socketType, const std::vector< Address > &addresses, Options... options) -> Socket
 Creates a socket that is connected to the first available address in a list.
 
template<tools::OneOf< NonBlockingTag, Protocol, DefaultPort, WithPort, AddressFamily, Timeout, WithStopSource >... Options>
static auto connectedSocket (int socketType, std::string_view hostName, Options... options) -> Socket
 Creates a socket that is connected to a named host.
 
template<tools::OneOf< NonBlockingTag, Protocol, AddressFamily, Backlog >... Options>
static auto listeningSocket (int socketType, PortNumber portNumber, Options... options) -> Socket
 Creates socket that listens on all local interfaces.
 
template<tools::OneOf< NonBlockingTag, Protocol, Backlog >... Options>
static auto listeningSocket (int socketType, const Address &address, Options... options) -> Socket
 Creates socket that listens on a specific address.
 

Detailed Description

A socket.

See also
SocketDevice

Member Enumeration Documentation

◆ Direction

Directions for sutdown().

Enumerator
Read 

Shut down the read direction only.

Write 

Shut down the write direction only.

ReadWrite 

Shut down the read and write directions.

Constructor & Destructor Documentation

◆ Socket() [1/4]

xentara::utils::network::Socket::Socket ( )
defaultnoexcept

Default constructor.

Creates an invalid socket object.

◆ Socket() [2/4]

template<tools::OneOf< NonBlockingTag, Protocol >... Options>
xentara::utils::network::Socket::Socket ( int  addressFamily,
int  socketType,
Options...  options 
)

Constructor that creates a socket.

Note
This constructor allows you to specify a number of options for the socket, described under Option Parameters below. Just pass the options in the options parameter pack. To create a non-blocking TCP socket, for example, use the following call:
SOCK_STREAM,
A socket.
Definition Socket.hpp:49
Protocol
Marker for protocols.
Definition Options.hpp:122
constexpr NonBlockingTag kNonBlocking
A marker for creating non-blocking sockets.
Definition Options.hpp:147
Note
The original BSD socket specification distinguished between address families (AF_INET etc.) unsed for socket addresses and protocol families (PF_INET etc.) used for sockets. The man pages on FreeBSD, Darwin, and macOS consequently state that PF_XXX constants should be used when creating sockets, rather than AF_XXX constants. The POSIX socket standard, however, makes no mention of PF_XXX constants, and uses AF_XXX constants for both socket addresses and sockets. The documentation for Linux, WinSock, as well as OpenBSD and many other Unix flavours also use AF_XXX in both cases. We recommend using AF_XXX when creating sockets instead of PF_XXX so as to be POSIX compliant. This will also work on BSD style socket implementations, as the corresponding AF_XXX and PF_XXX defines are always the same.
Parameters
addressFamilyThe address family, also called the socket domain. Can be any of the AF_XXX address family defines, like AF_INET or AF_INET6.
socketTypeThe socket type of socket to create. Can be any of the SOCK_XXX socket type defines, like SOCK_STREAM or SOCK_DGRAM.
optionsThe options for the socket. See Option Parameters below.
Option Parameters
xentara::utils::network::kNonBlockingMake the socket non-blocking.
xentara::utils::network::Protocol(protocol)Specifies that the socket should use the protocol protocol. protocol can be any of the XXXPROTO_YYY protocol defines, like IPPROTO_TCP or IPPROTO_SCTP. If you do not specify this option, or if you specify 0 for the protocol, then a suitable protocol will be selected based on the address family and socket type, if possible.
Exceptions
std::runtime_errorAn error occurred getting the option
std::invalid_argumentAn address family of AF_UNSPEC was specified
std::invalid_argumentA socket type of 0 was specified

◆ Socket() [3/4]

xentara::utils::network::Socket::Socket ( posix::File  socketFileDescriptor)
noexcept

Conversion from a Posix file descriptor.

This constructor takes ownership of the socket.

Note
This constructor is not available under Windows.
Parameters
socketFileDescriptorThe file descriptor of the new socket, or -1 to create a object that does not contain a socket.

◆ Socket() [4/4]

xentara::utils::network::Socket::Socket ( windows::Socket  socket)
noexcept

Conversion from a native socket.

This constructor takes ownership of the socket.

Note
This constructor is only available under Windows.
Parameters
socketThe new socket, or INVALID_SOCKET to create a object that does not contain a socket.

Member Function Documentation

◆ accept()

template<tools::OneOf< NonBlockingTag >... Options>
auto xentara::utils::network::Socket::accept ( Options...  options) const -> Socket

Accepts a connection from a socket in listening mode.

This function may only be called on sockets that have previously been put into listening mode using listen()

Note
This function allows you to specify the option xentara::utils::network::kNonBlocking make the socket non-blocking. To accept a connection as a non-blocking socket, use the following call:
static auto listeningSocket(int socketType, PortNumber portNumber, Options... options) -> Socket
Creates socket that listens on all local interfaces.
Parameters
optionsThe Options to use for the socket. See Option Parameters below.
Option Parameters
xentara::utils::network::kNonBlockingMake the accepted socket non-blocking.
Returns
Returns the newly accepted socket. If the listening socket is non-blocking, and no connections were pending, a default constructed socket is returned. You can use the operator bool() to check whether the returned socket is valid.
Exceptions
std::runtime_errorAn error occurred accepting the connection, or the socket is not in listening mode

◆ addressFamily()

auto xentara::utils::network::Socket::addressFamily ( ) const -> int
noexcept

Gets the address family of the socket, also called the socket domain.

Returns
The address family. This will be one of the AF_XXX address family defines, like AF_INET or AF_INET6. For default constructed objects, or if the address family could not be determined, this function returns AF_UNSPEC.

◆ bind() [1/2]

auto xentara::utils::network::Socket::bind ( const Address address) -> void

Binds the socket to a specific address.

Parameters
addressThe address to bind to. If you specify an address returned by Address::any(), then the socket will be bound to the relevant port on all local interfaces.
Exceptions
std::runtime_errorAn error occurred binding the socket
std::invalid_argumentThe address is default constructed, or has an address family of AF_UNSPEC.

◆ bind() [2/2]

auto xentara::utils::network::Socket::bind ( PortNumber  portNumber) -> void

Binds the socket to a port number on all local interfaces.

Parameters
portNumberThe port number to bind to, or 0 to allow the network stack to assign a port number. For protocols that do not use port numbers, the port should always be 0.
Exceptions
std::runtime_errorAn error occurred binding the socket

◆ close()

auto xentara::utils::network::Socket::close ( ) -> void
noexcept

Closes the socket, if one is open.

◆ compatibleSocket()

template<tools::OneOf< NonBlockingTag, Protocol >... Options>
static auto xentara::utils::network::Socket::compatibleSocket ( int  socketType,
const Address address,
Options...  options 
) -> Socket
static

Creates a socket that is compatible with an address.

This function creates a socket that can be used to listen to or communicate with a certain address. The socket will not actually be bound or connected to the address, use bind() or connect() if you need to bind to or connect to the address.

Note
This function allows you to specify a number of options for the socket, described under Option Parameters below. Just pass the options in the options parameter pack. To create a non-blocking TCP socket, for example, use the following call:
address,
static auto compatibleSocket(int socketType, const Address &address, Options... options) -> Socket
Creates a socket that is compatible with an address.
Parameters
socketTypeThe type of socket to create. Can be any of the SOCK_XXX socket type defines, like SOCK_STREAM or SOCK_SEQPACKET.
addressThe addresses that the socket will be used for.
optionsThe Options to use for the socket. See Option Parameters below.
Option Parameters
xentara::utils::network::kNonBlockingMake the socket non-blocking.
xentara::utils::network::Protocol(protocol)Specifies that the socket should use the protocol protocol. protocol can be any of the XXXPROTO_YYY protocol defines, like IPPROTO_TCP or IPPROTO_SCTP. If you do not specify this option, or if you specify 0 for the protocol, then a suitable protocol will be selected based on the address and the socket type, if possible.
Returns
A socket connected to the address
Exceptions
std::runtime_errorAn error occurred creating or connecting the socket for all of the given addresses
std::invalid_argumentA socket type of 0 was specified
std::invalid_argumentThe address is default constructed, or has an address family of AF_UNSPEC.

◆ connect()

auto xentara::utils::network::Socket::connect ( const Address address) -> bool

Connects to an address.

Parameters
addressThe address to connect to
Returns
returns true if the connection was establishen, or false if the socket is non-blocking and the connection is pending.
Exceptions
std::runtime_errorAn error occurred connecting the socket
std::invalid_argumentThe address is default constructed, or has an address family of AF_UNSPEC.

◆ connectedSocket() [1/3]

template<tools::OneOf< NonBlockingTag, Protocol, Timeout, WithStopSource >... Options>
static auto xentara::utils::network::Socket::connectedSocket ( int  socketType,
const Address address,
Options...  options 
) -> Socket
static

Creates a socket that is connected to an address.

Note
This function allows you to specify a number of options for the socket, described under Option Parameters below. Just pass the options in the options parameter pack. To connect a non-blocking socket to a list of addresses using a timeout of 5s, for example, use the following call:
address,
static auto connectedSocket(int socketType, const Address &address, Options... options) -> Socket
Creates a socket that is connected to an address.
Marker for timeout value.
Definition Options.hpp:188
Parameters
socketTypeThe type of socket to create. Can be any of the SOCK_XXX socket type defines, like SOCK_STREAM or SOCK_SEQPACKET.
addressThe addresses to connect to.
optionsThe Options to use for the connection. See Option Parameters below.
Option Parameters
xentara::utils::network::kNonBlockingMake the socket non-blocking after the connection has been established. Since the socket will only be made non-blocking after it is connected, the connection process itself will always block. To connect a socket without blocking, create a non-blocking socket manually, and connect it using the non-static connect() function.
xentara::utils::network::Protocol(protocol)Specifies that the connection should be established using the protocol protocol. protocol can be any of the XXXPROTO_YYY protocol defines, like IPPROTO_TCP or IPPROTO_SCTP. If you do not specify this option, or if you specify 0 for the protocol, then a suitable protocol will be selected based on the address and the socket type, if possible.
xentara::utils::network::Timeout(timeout)Specifies the timeout for the connect. If you do not specify this option, or if you specify std::nullopt for the timeout, an infinite timeout will be used.
xentara::utils::network::WithStopSource(stopSource)Specifies the stop source to watch for stop requests. The stop source can be used to interrupt the wait, usually to shutdown and close the socket. If the stop source is triggered, the function will throw an exception of type io::StopRequested. If you do not specify this option, no stop source will be used.
Returns
A socket connected to the given address. If you specified a timeout, and the connection could not be completed within in the given time, a default constructed socket is returned. You can use the operator bool() to check whether the returned socket is valid.
Exceptions
io::StopRequestedA stop source was specified, and the stop source was triggered.
std::runtime_errorAn error occurred creating or connecting the socket for all of the given addresses
std::invalid_argumentA socket type of 0 was specified
std::invalid_argumentThe address is default constructed, or has an address family of AF_UNSPEC.

◆ connectedSocket() [2/3]

template<tools::OneOf< NonBlockingTag, Protocol, Timeout, WithStopSource >... Options>
static auto xentara::utils::network::Socket::connectedSocket ( int  socketType,
const std::vector< Address > &  addresses,
Options...  options 
) -> Socket
static

Creates a socket that is connected to the first available address in a list.

Note
This function allows you to specify a number of options for the socket, described under Option Parameters below. Just pass the options in the options parameter pack. To connect a non-blocking socket to a list of addresses using the TCP protocol, for example, use the following call:
Parameters
socketTypeThe type of socket to create. Can be any of the SOCK_XXX socket type defines, like SOCK_STREAM or SOCK_SEQPACKET.
addressesThe addresses to try to connect to, in the order that they should be tried. Addresses that do not support the given socket type are ignored, as are default constructed addresses and addresses with address family AF_UNSPEC.
optionsThe Options to use for the connection. See Option Parameters below.
Option Parameters
xentara::utils::network::kNonBlockingMake the socket non-blocking after the connection has been established. Since the socket will only be made non-blocking after it is connected, the connection process itself will always block. To connect a socket without blocking, create a non-blocking socket manually, and connect it using the non-static connect() function.
xentara::utils::network::Protocol(protocol)

Specifies that the connection should be established using the protocol protocol. protocol can be any of the XXXPROTO_YYY protocol defines, like IPPROTO_TCP or IPPROTO_SCTP. If you do not specify this option, or if you specify 0 for the protocol, then a suitable protocol will be selected based on the address and the socket type, if possible.

xentara::utils::network::Timeout(timeout)Specifies the timeout for the connect. If you do not specify this option, or if you specify std::nullopt for the timeout, an infinite timeout will be used.
xentara::utils::network::WithStopSource(stopSource)Specifies the stop source to watch for stop requests. The stop source can be used to interrupt the wait, usually to shutdown and close the socket. If the stop source is triggered, the function will throw an exception of type io::StopRequested. If you do not specify this option, no stop source will be used.
Returns
A socket connected to the first address that accepted the connection. If you specified a timeout, and the connection could not be completed within in the given time, a default constructed socket is returned. You can use the operator bool() to check whether the returned socket is valid.
Exceptions
HostNotFoundErrorThe address list did not contain any suitable addresses.
io::StopRequestedA stop source was specified, and the stop source was triggered.
std::runtime_errorAn error occurred creating or connecting the socket for all of the given addresses
std::invalid_argumentA socket type of 0 was specified

◆ connectedSocket() [3/3]

template<tools::OneOf< NonBlockingTag, Protocol, DefaultPort, WithPort, AddressFamily, Timeout, WithStopSource >... Options>
static auto xentara::utils::network::Socket::connectedSocket ( int  socketType,
std::string_view  hostName,
Options...  options 
) -> Socket
static

Creates a socket that is connected to a named host.

Normally, hostName must contain a port number after the host name or address string. You can pass the options xentara::utils::network::DefaultPort or xentara::utils::network::WithPort in the options parameter pack to make the port number optional, or to specify a fixed port number. See Option Parameters below for a description of these options.

Note
This function allows you to specify a number of options for the socket and the address lookup, described under Option Parameters below. Just pass the options in the options parameter pack. To connect a non-blocking socket to a host name using a default port of 8080, for example, use the following call:
hostName,
DefaultPort
Marker for host names/address strings with optional port number.
Definition Options.hpp:62
Parameters
socketTypeThe type of socket to create. Can be any of the SOCK_XXX socket type defines, like SOCK_STREAM or SOCK_SEQPACKET.
hostNameThe host name to connect to
optionsThe Options to use for the connection. See Option Parameters below.
Option Parameters
xentara::utils::network::kNonBlockingMake the socket non-blocking after the connection has been established. Since the socket will only be made non-blocking after it is connected, the connection process itself will always block. To connect a socket without blocking, create a non-blocking socket manually, and connect it using the non-static connect() function.
xentara::utils::network::Protocol(protocol)Specifies that the connection should be established using the protocol protocol. protocol can be any of the XXXPROTO_YYY protocol defines, like IPPROTO_TCP or IPPROTO_SCTP. If you do not specify this option, or if you specify 0 for the protocol, then a suitable protocol will be selected based on the address family and socket type, if possible.
xentara::utils::network::DefaultPort(portNumber)Specifies that including port number in hostName is optional. If hostName does not contain a port number, portNumber will be used instead. Cannot be combined with xentara::utils::network::WithPort.
xentara::utils::network::WithPort(portNumber)Specifies that hostName must be a host name or address string, and may not contain a port number. The connection will be established on port number portNumber. This option Cannot be combined with xentara::utils::network::DefaultPort.
xentara::utils::network::AddressFamily(addressFamily)Specifies a that the connection may only be established using addresses with the address family addressFamily. addressFamily can be any of the AF_XXX address family defines, like AF_INET or AF_INET6. If you do not specify this option, or if you specify AF_UNSPEC for the address family, then addresses of any address family are tried. You should usually not use this option, to allow communication over both IPv4 and IPv6. Only use this option if you are planning to communicate with legacy software that does not support IPv6.
xentara::utils::network::Timeout(timeout)Specifies the timeout for the connect. If you do not specify this option, or if you specify std::nullopt for the timeout, an infinite timeout will be used.
xentara::utils::network::WithStopSource(stopSource)Specifies the stop source to watch for stop requests. The stop source can be used to interrupt the wait, usually to shutdown and close the socket. If the stop source is triggered, the function will throw an exception of type io::StopRequested. If you do not specify this option, no stop source will be used.
Returns
A socket connected to the host name. If you specified a timeout, and the connection could not be completed within in the given time, a default constructed socket is returned. You can use the operator bool() to check whether the returned socket is valid.
Exceptions
io::StopRequestedA stop source was specified, and the stop source was triggered.
std::runtime_errorAn error occurred creating or connecting the socket
std::invalid_argumentA socket type of 0 was specified

◆ description()

auto xentara::utils::network::Socket::description ( ) const -> std::string_view
noexcept

Gets a description for the socket.

This function can be used in error messages to describe the socket. It will return a string like “TCP/IP socket”.

Returns
A short string describing the socket

◆ error()

auto xentara::utils::network::Socket::error ( ) const -> std::error_code

Returns the error status, and clears it.

This function can be used to retreive the error if poll() returned POLLERR.

Fetching the error status clears it. This is why this function is not const.

Returns
The error status.
Exceptions
std::runtime_errorAn error occurred getting the error status.

◆ getOption()

template<typename Value >
auto xentara::utils::network::Socket::getOption ( int  level,
int  optionName,
std::nothrow_t   
) const -> xentara::utils::eh::expected< Value, std::error_code >
noexcept

Gets a socket option.

This function behaves the same as option(), but returns an error code on error instead of throwing an exception. Use this function if you want to do your own error handling, like throwing an exception with a more descriptive what() string.

Template Parameters
ValueThe type of the socket option's value. Each option requires a specific type of value. Refer to the documentation for the appropriate option for the supported types.
Parameters
levelThe level at which the option resides. Must be SOL_SOCKET to get a socket level option, or one of the XXXPROTO_YYY protocol defines, like IPPROTO_TCP or IPPROTO_SCTP, to get a protocol level options. Other socket levels may also be defined by the operating system.
optionNameThe name of the option. This is an option level specific integer that describes which option to set.
Returns
The value of the option, or an error code on error

◆ listen()

template<tools::OneOf< Backlog >... Options>
auto xentara::utils::network::Socket::listen ( Options...  options) -> void

Puts the socket into listening mode.

This function puts the socket into listening mode, so that is can accept incoming connections. For most protocols, a socket must be bound to a local port using bind() before it can be put into the listening state.

Note
This function allows you to specify a non-standard backlog using the option xentara::utils::network::Backlog. To listen using a backlog of 1, use the following call:
Marker for listening backlog.
Definition Options.hpp:159
Parameters
optionsThe Options to use for listening. See Option Parameters below.
Option Parameters
xentara::utils::network::BacklogSpecifies a custom backlog. If you do not specify this option, then a backlog of 128 will be used.
Exceptions
std::runtime_errorAn error occurred putting the socket into listening mode
std::invalid_argumentA backlog of less than 1 was specified.

◆ listeningSocket() [1/2]

template<tools::OneOf< NonBlockingTag, Protocol, Backlog >... Options>
static auto xentara::utils::network::Socket::listeningSocket ( int  socketType,
const Address address,
Options...  options 
) -> Socket
static

Creates socket that listens on a specific address.

This function creates a socket, binds it to the given address, and puts it into the listening state so that it can accept connections.

Note
This function allows you to specify a number of options for the socket, described under Option Parameters below. Just pass the options in the options parameter pack. To create a non-blocking socket that is listening on a specific address using a backlog of 5, for example, use the following call:
Parameters
socketTypeThe type of socket to create. Must be a SOCK_XXX socket type define for a socket type that supports listening, like SOCK_STREAM or SOCK_SEQPACKET.
addressThe address to listen on. If you specify an address returned by Address::any(), then the socket will listen to the relevant port on all local interfaces.
optionsThe Options to use. See Option Parameters below.
Option Parameters
xentara::utils::network::kNonBlockingMake the socket non-blocking.
xentara::utils::network::Protocol(protocol)Specifies that the connection should listen using the protocol protocol. protocol can be any of the XXXPROTO_YYY protocol defines, like IPPROTO_TCP or IPPROTO_SCTP. If you do not specify this option, or if you specify 0 for the protocol, then a suitable protocol will be selected based on the address and the socket type, if possible.
xentara::utils::network::BacklogSpecifies a custom backlog. If you do not specify this option, then a backlog of 128 will be used.
Returns
A socket listening in the port
Exceptions
std::runtime_errorAn error occurred creating the socket, or putting it into the listening state.
std::invalid_argumentA socket type of 0 was specified
std::invalid_argumentThe address is default constructed, or has an address family of AF_UNSPEC.
std::invalid_argumentA backlog of less than 1 was specified.

◆ listeningSocket() [2/2]

template<tools::OneOf< NonBlockingTag, Protocol, AddressFamily, Backlog >... Options>
static auto xentara::utils::network::Socket::listeningSocket ( int  socketType,
PortNumber  portNumber,
Options...  options 
) -> Socket
static

Creates socket that listens on all local interfaces.

This function creates a socket, binds it to the given port on all local interfaces, and puts it into the listening state, so that it can accept connections.

Note
This function allows you to specify a number of options for the socket, described under Option Parameters below. Just pass the options in the options parameter pack. To create a non-blocking socket that is listening on a specific port using a backlog of 5, for example, use the following call:
Parameters
socketTypeThe type of socket to create. Must be a SOCK_XXX socket type define for a socket type that supports listening, like SOCK_STREAM or SOCK_SEQPACKET.
portNumberThe port number to bind to, or 0 to allow the network stack to assign a port number. For protocols that do not use port numbers, the port should always be 0.
optionsThe Options to use. See Option Parameters below.
Option Parameters
xentara::utils::network::kNonBlockingMake the socket non-blocking.
xentara::utils::network::Protocol(protocol)Specifies that the connection should listen using the protocol protocol. protocol can be any of the XXXPROTO_YYY protocol defines, like IPPROTO_TCP or IPPROTO_SCTP. If you do not specify this option, or if you specify 0 for the protocol, then a suitable protocol will be selected based on the address family and socket type, if possible.
xentara::utils::network::AddressFamily(addressFamily)Specifies a that the socket should only listen for connections for the address family addressFamily. addressFamily can be any of the AF_XXX address family defines, like AF_INET or AF_INET6. If you do not specify this option, or if you specify AF_UNSPEC for the address family, then the address family is automatically selected. You should usually not use this option, to allow connections over both IPv4 and IPv6. Only use this option if you need to restrict listening to only IPv6 or only IPv4.
xentara::utils::network::BacklogSpecifies a custom backlog. If you do not specify this option, then a backlog of 128 will be used.
Returns
A socket listening in the port
Exceptions
std::runtime_errorAn error occurred creating the socket, or putting it into the listening state.
std::invalid_argumentA socket type of 0 was specified
std::invalid_argumentA backlog of less than 1 was specified.

◆ localAddress()

auto xentara::utils::network::Socket::localAddress ( ) const -> Address

Gets the local address of a bound or connected socket.

Returns
The local address of the socket.
Exceptions
std::runtime_errorAn error occurred getting the socket address, or the socket is not bound and not connected.

◆ makeNonBlocking()

auto xentara::utils::network::Socket::makeNonBlocking ( bool  nonBlocking = true) -> void

Sets the non-blocking option of the socket.

This function allows you to make a socket blocking or non-blocking after it has been created. To create a socket that is non-blocking from the start, simply pass the kNonBlocking option to the constructor.

Parameters
nonBlockingtrue to make the socket non-blocking, or false to make is blocking.
Exceptions
std::runtime_errorAn error occurred setting the option

◆ native() [1/2]

auto xentara::utils::network::Socket::native ( ) const -> int
noexcept

Gets the underlying Posix file descriptor for the socket.

Note
This function is not available under Windows.
Returns
The file descriptor, or -1 if no socket is open.

◆ native() [2/2]

auto xentara::utils::network::Socket::native ( ) const -> SOCKET
noexcept

Gets the underlying Windows Sockets 2 SOCKET.

Note
This function is only available under Windows.
Returns
The native socket, or INVALID_SOCKET if no socket is open.

◆ operator bool()

xentara::utils::network::Socket::operator bool ( ) const
explicitnoexcept

Checks whether the object contains a valid socket.

Returns
Returns true if the object contains a valid socket, or false if the object is default constructed, has been released using release(), or moved away using std::move() etc.

◆ option()

template<typename Value >
auto xentara::utils::network::Socket::option ( int  level,
int  optionName 
) const -> Value

Gets a socket option.

Template Parameters
ValueThe type of the socket option's value. Each option requires a specific type of value. Refer to the documentation for the appropriate option for the supported types.
Parameters
levelThe level at which the option resides. Must be SOL_SOCKET to get a socket level option, or one of the XXXPROTO_YYY protocol defines, like IPPROTO_TCP or IPPROTO_SCTP, to get a protocol level options. Other socket levels may also be defined by the operating system.
optionNameThe name of the option. This is an option level specific integer that describes which option to set.
Returns
The value of the option
Exceptions
std::runtime_errorAn error occurred getting the option

◆ performOverlappedIo() [1/2]

auto xentara::utils::network::Socket::performOverlappedIo ( functional::function_ref< auto(SOCKET, OVERLAPPED *) → BOOL >  operation,
HANDLE  event,
std::optional< std::chrono::nanoseconds timeout = std::nullopt 
) -> std::optional<DWORD>

Performs an overlapped I/O operation.

This function creates an OVERLAPPED structure and calls a function object with it. The function object must call a Windows overlapped socket function like WSARecv() or WSASend(), passing the overlapped structure to it, and return the result. The function must also preserve the error code stored in GetLastError(), specifically the error code ERROR_IO_PENDING, which the function uses to determine if waiting is necessary.

Note
This function is only available under Windows.
Parameters
operationThe operation to perform. operation will be called with the socket and an overlapped structure as parameters. It must return TRUE on success or FALSE on error. If FALSE is returned, the last error code must be set to an appropriate error. If an overlapped I/O operation is pending, the function must return FALSE and set the last error to ERROR_IO_PENDING in the manner of overlapped I/O functions like WSARecv() and WSASend().
Precondition
The socket must be an overlapped socket. Windows sockets are overlapped by default, unless you created the socket using WSASocket() and didn’t specify WSA_FLAG_OVERLAPPED in dwFlags.
Parameters
eventThe event to use in the OVERLAPPED structure.
timeoutThe timeout, or std::nullopt for infinite. Negative timeouts are treated the same as a timeout of 0.
Returns

Returns the number of bytes transferred on success, or std::nullopt on error. To get extended error information, call GetLastError(). On timeout, the last error is set to ERROR_OPERATION_ABORTED.

The meaning of “number of bytes transferred” depends on the overlapped operation. See the documentation of the lpNumberOfBytesTransferred parameter of GetOverlappedResult().

See also
Synchronization and Overlapped Input and Output in the Windows technical documentation

◆ performOverlappedIo() [2/2]

auto xentara::utils::network::Socket::performOverlappedIo ( functional::function_ref< auto(SOCKET, OVERLAPPED *) → BOOL >  operation,
std::span< HANDLE >  waitObjects,
std::optional< std::chrono::nanoseconds timeout = std::nullopt 
) -> std::optional<windows::OverlappedResult>

Performs an overlapped I/O operation.

This function creates an OVERLAPPED structure and calls a function object with it. The function object must call a Windows overlapped socket function like WSARecv() or WSASend(), passing the overlapped structure to it, and return the result. The function must also preserve the error code stored in GetLastError(), specifically the error code ERROR_IO_PENDING, which the function uses to determine if waiting is necessary.

Note
This function is only available under Windows.
Parameters
operationThe operation to perform. operation will be called with the socket and an overlapped structure as parameters. It must return TRUE on success or FALSE on error. If FALSE is returned, the last error code must be set to an appropriate error. If an overlapped I/O operation is pending, the function must return FALSE and set the last error to ERROR_IO_PENDING in the manner of overlapped I/O functions like WSARecv() and WSASend().
Precondition
The socket must be an overlapped socket. Windows sockets are overlapped by default, unless you created the socket using WSASocket() and didn’t specify WSA_FLAG_OVERLAPPED in dwFlags.
Parameters
waitObjectsThe objects to wait for. The first position in the span must contain the event to use in the OVERLAPPED structure.
timeoutThe timeout, or std::nullopt for infinite. Negative timeouts are treated the same as a timeout of 0.
Returns
Returns the result of the operation on success, or std::nullopt on error. To get extended error information, call GetLastError(). On timeout, the last error is set to ERROR_OPERATION_ABORTED.
Exceptions
std::invalid_argumentwaitObjects is empty, or contains more objects than Windows can handle.
See also
Synchronization and Overlapped Input and Output in the Windows technical documentation

◆ poll() [1/4]

auto xentara::utils::network::Socket::poll ( short  events,
const io::StopSource stopSource,
std::optional< std::chrono::nanoseconds timeout = std::nullopt 
) const -> short

Waits for events on the socket using a stop source.

This function provides an interruptible way to wait for events on a socket. The stop source can be used to interrupt the wait, usually to shutdown and close the socket. If the stop source is triggered, the function will throw an exception of type io::StopRequested.

Note
This function is not available under Windows, as Windows does not support interrupting polls.
Parameters
eventsThe events to wait for. Must be a bit combination of the POLXXX poll event defines, like POLLIN or POLLOUT.
stopSourceThe stop source to watch for stop requests.
timeoutThe timeout, or std::nullopt to wait without timeout.
Returns
The events that actually occurred, or 0 on timeout.
Exceptions
io::StopRequestedThe stop source was triggered.
std::runtime_errorAn error occurred waiting for the events.

◆ poll() [2/4]

auto xentara::utils::network::Socket::poll ( short  events,
std::optional< std::chrono::nanoseconds timeout = std::nullopt 
) const -> short

Waits for events on the socket.

Parameters
eventsThe events to wait for. Must be a bit combination of the POLXXX poll event defines, like POLLIN or POLLOUT.
timeoutThe timeout, or std::nullopt to wait without timeout.
Returns
The events that actually occurred, or 0 on timeout.
Exceptions
std::runtime_errorAn error occurred waiting for the events.

◆ poll() [3/4]

static auto xentara::utils::network::Socket::poll ( std::span< pollfd >  sockets,
const io::StopSource stopSource,
std::optional< std::chrono::nanoseconds timeout = std::nullopt 
) -> bool
static

Waits for events on one or more sockets using a stop source.

This function provides an interruptible way to wait for events on one or more sockets. The stop source can be used to interrupt the wait, usually to shutdown and close the sockets. If the stop source is triggered, the function will throw an exception of type io::StopRequested.

Note
This function is not available under Windows, as Windows does not support interrupting polls.
Parameters
sockets

The sockets and event to wait for. The revents member of the sockets is set to the events that were actually received.

Under Posix, the fd membner of the pollfd structures can hold any type of file descriptor, so this function can be used to wait on pipes and other types of file descriptors. Under Windows, only actual sockets can be used.

stopSourceThe stop source to watch for stop requests.
timeoutThe timeout, or std::nullopt to wait without timeout.
Returns
true if any events actually occurred on any of the sockets, or false on timeout.
Exceptions
io::StopRequestedThe stop source was triggered.
std::runtime_errorAn error occurred waiting for the events.

◆ poll() [4/4]

static auto xentara::utils::network::Socket::poll ( std::span< pollfd >  sockets,
std::optional< std::chrono::nanoseconds timeout = std::nullopt 
) -> bool
static

Waits for events on one or more sockets.

Parameters
sockets

The sockets and event to wait for. The revents member of the sockets is set to the events that were actually received.

Under Posix, the fd membner of the pollfd structures can hold any type of file descriptor, so this function can be used to wait on pipes and other types of file descriptors. Under Windows, only actual sockets can be used.

timeoutThe timeout, or std::nullopt to wait without timeout.
Returns
true if any events actually occurred on any of the sockets, or false on timeout.
Exceptions
std::runtime_errorAn error occurred waiting for the events.

◆ protocol()

auto xentara::utils::network::Socket::protocol ( ) const -> int
noexcept

Gets the protocol of the socket.

Returns
The protocol. XXXPROTO_YYY protocol defines, like IPPROTO_TCP or IPPROTO_SCTP. For default constructed objects, or if the protocol could not be determined, this function returns 0.

◆ receive()

auto xentara::utils::network::Socket::receive ( void *  buffer,
std::size_t  size,
int  flags = 0 
) const -> std::optional< std::size_t >

Receive data from the socket.

Parameters
bufferA pointer to the buffer that will receive the data
sizeThe size of the buffer.
flagsThe flags. This can be a combination of operationg system receive flags, like MSG_PEEK or MSG_OOB.
Returns
The number of bytes actually read, or std::nullopt, if no data is available without blocking. If the socket was gracefully closed from the remote side, 0 is returned. 0 is also returned if size is 0.
Exceptions
std::runtime_errorAn error occurred reading from the socket.

◆ receiveFrom()

auto xentara::utils::network::Socket::receiveFrom ( void *  buffer,
std::size_t  size,
int  flags = 0 
) const -> std::pair< std::optional< std::size_t >, Address >

Receive data from the socket and returns the sender address.

Parameters
bufferA pointer to the buffer that will receive the data
sizeThe size of the buffer.
flagsThe flags. This can be a combination of operationg system receive flags, like MSG_PEEK or MSG_OOB.
Returns

The number of bytes actually read, together with the address of the sender. If no data is available without blocking, std::nullopt is returned, together with a default-consructed address object.

For stream oriented sockets, a size of 0 is returned if the socket was gracefully closed from the remote side. For datagram sockets, a size of 0 is returned in first if a zero-length datagram was received.

0 is also returned for the size if size is 0.

Exceptions
std::runtime_errorAn error occurred reading from the socket.

◆ release() [1/2]

auto xentara::utils::network::Socket::release ( ) -> int
noexcept

Removes the the socket and passes ownership to the caller.

After this call, this object will no longer contain a socket.

Note
This function is not available under Windows.
Returns
The file descriptor of the socket, or -1 if no socket was open. The caller must assume ownership of the file descriptor and close it when it is no longer needed.

◆ release() [2/2]

auto xentara::utils::network::Socket::release ( ) -> SOCKET
noexcept

Removes the socket and passes ownership to the caller.

After this call, this object will no longer contain a socket.

Note
This function is only available under Windows.
Returns
The native socket, or INVALID_SOCKET if the socket is open. The caller must assume ownership of the socket and close it when it is no longer needed.

◆ remoteAddress()

auto xentara::utils::network::Socket::remoteAddress ( ) const -> Address

Gets the address that the socket is connected to.

Returns
The remote address of the socket.
Exceptions
std::runtime_errorAn error occurred getting the socket address, or the socket is not connected.

◆ send()

auto xentara::utils::network::Socket::send ( const void *  data,
std::size_t  size,
int  flags = 0 
) const -> std::size_t

Sends data to the socket.

Parameters
dataA pointer to the data to send
sizeThe size of the data.
flagsThe flags. This can be a combination of operationg system send flags, like MSG_DONTROUTE or MSG_OOB. Under Posix, MSG_NOSIGNAL is automatically added.
Returns
The number of bytes actually sent, or 0, if no data is available without blocking. 0 is also returned if size is 0.
Exceptions
std::runtime_errorAn error occurred writing to the socket.
ConnectionClosedErrors thrown because the connection was closed are derived from ConnectionClosed in addition to std::runtime_error.

◆ sendTo()

auto xentara::utils::network::Socket::sendTo ( const void *  data,
std::size_t  size,
const Address destination,
int  flags = 0 
) const -> std::size_t

Sends data to a specific destination over the socket.

Parameters
dataA pointer to the data to send
sizeThe size of the data.
destinationThe destination address. Must be compatible with the socket.
Returns
The number of bytes actually sent, or 0, if no data is available without blocking. 0 is also returned if size is 0.
Parameters
flagsThe flags. This can be a combination of operationg system send flags, like MSG_DONTROUTE or MSG_OOB. Under Posix, MSG_NOSIGNAL is automatically added.
Exceptions
std::runtime_errorAn error occurred writing to the socket.
ConnectionClosedErrors thrown because the connection was closed are derived from ConnectionClosed in addition to std::runtime_error.

◆ setOption() [1/2]

template<typename Value >
auto xentara::utils::network::Socket::setOption ( int  level,
int  optionName,
const Value &  value 
) -> void

Sets a socket option.

Template Parameters
ValueThe type of the socket option's value. Each option requires a specific type of value. Refer to the documentation for the appropriate option for the supported types.
Parameters
levelThe level at which the option resides. Must be SOL_SOCKET to set a socket level option, or one of the XXXPROTO_YYY protocol defines, like IPPROTO_TCP or IPPROTO_SCTP, to set a protocol level option. Other socket levels may also be defined by the operating system.
optionNameThe name of the option. This is an option level specific integer that describes which option to set.
valueThe value to set
Exceptions
std::runtime_errorAn error occurred setting the option

◆ setOption() [2/2]

template<typename Value >
auto xentara::utils::network::Socket::setOption ( int  level,
int  optionName,
const Value &  value,
std::nothrow_t   
) -> std::error_code
noexcept

Sets a socket option without throwing exceptions.

This function behaves the same as setOption(), but returns an error code on error instead of throwing an exception. Use this function if you want to do your own error handling, like throwing an exception with a more descriptive what() string.

Parameters
levelThe level at which the option resides. Must be SOL_SOCKET to get a socket level option, or one of the XXXPROTO_YYY protocol defines, like IPPROTO_TCP or IPPROTO_SCTP, to get a protocol level options. Other socket levels may also be defined by the operating system.
optionNameThe name of the option. This is an option level specific integer that describes which option to set.
valueThe value to set
Returns
Returns an error code on error, or std::error_code() on success.

◆ shutdown()

auto xentara::utils::network::Socket::shutdown ( Direction  directions = Direction::ReadWrite) -> void

Shuts down the socket.

Parameters
directionsWhich directions to shut down.
Exceptions
std::runtime_errorAn error occurred.

◆ socketType()

auto xentara::utils::network::Socket::socketType ( ) const -> int
noexcept

Gets the socket type.

Returns
The socket type. This will be one of the SOCK_XXX socket type defines, like SOCK_STREAM or SOCK_DGRAM. For default constructed objects, or if the socket type could not be determined, this function returns 0.

◆ throwError()

template<std::derived_from< std::system_error > Exception, typename... ExceptionArguments>
auto xentara::utils::network::Socket::throwError ( ExceptionArguments &&...  exceptionArguments) -> void

Throws an exception if the socket contains an error.

This function can be used to throw an exception if poll() returned POLLERR.

Fetching the error status clears it. This is why this function is not const.

Exceptions
std::runtime_errorAn error occurred getting the error status.

◆ waitForEvent()

auto xentara::utils::network::Socket::waitForEvent ( short  events,
const io::StopSource stopSource,
std::optional< std::chrono::nanoseconds timeout = std::nullopt 
) const -> short

Waits for an event on the socket, using a timeout.

This function provides an interruptible way to wait for events on a socket. The stop source can be used to interrupt the wait, usually to shutdown and close the socket. If the stop source is triggered, the function will throw an exception of type io::StopRequested.

Note
This function is not available under Windows.
Parameters
eventsThe events to wait for. Must be a bit combination of the POLXXX poll event defines, like POLLIN or POLLOUT.
stopSourceThe stop source to watch for stop requests.
timeoutThe timeout, or std::nullopt to wait without timeout.
Returns
The events that actually occurred, or 0 on timeout.
Exceptions
io::StopRequestedThe stop source was triggered.
std::runtime_errorAn error occurred waiting for the events.