jsocketpp 1.0
A cross-platform C++20 socket library.
Loading...
Searching...
No Matches
jsocketpp::DatagramSocket Class Reference

Cross-platform UDP socket class with Java-style interface. More...

#include <DatagramSocket.hpp>

Inheritance diagram for jsocketpp::DatagramSocket:
Collaboration diagram for jsocketpp::DatagramSocket:

Public Member Functions

 DatagramSocket (Port localPort=0, std::string_view localAddress="", std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt, bool reuseAddress=true, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool nonBlocking=false, bool dualStack=true, bool autoBind=true, bool autoConnect=false, std::string_view remoteAddress="", Port remotePort=0, int connectTimeoutMillis=-1)
 Creates a UDP socket, optionally binds to a local address, and optionally connects to a remote peer.
 ~DatagramSocket () noexcept override
 Destructor for DatagramSocket. Ensures socket resources are released.
 DatagramSocket (const DatagramSocket &)=delete
 Copy constructor (deleted) for DatagramSocket.
DatagramSocketoperator= (const DatagramSocket &)=delete
 Copy assignment operator (deleted) for DatagramSocket.
 DatagramSocket (DatagramSocket &&rhs) noexcept
 Move constructor for DatagramSocket.
DatagramSocketoperator= (DatagramSocket &&rhs) noexcept
 Move assignment operator for DatagramSocket.
void bind ()
 Binds the datagram socket to all available interfaces on an ephemeral port.
void bind (Port localPort)
 Binds the datagram socket to a specific local port on all network interfaces.
void bind (std::string_view localAddress, Port localPort)
 Binds the datagram socket to a specific local IP address and port.
bool isBound () const noexcept
 Indicates whether the datagram socket has been explicitly bound to a local address or port.
void connect (std::string_view host, Port port, int timeoutMillis)
 Connect this UDP socket to a default peer (set the default destination).
void disconnect ()
 Disconnect this UDP socket from its current default peer.
bool isConnected () const noexcept
 Indicates whether the datagram socket is connected to a specific remote peer.
std::string getLocalIp (bool convertIPv4Mapped)
 Return the local interface IP address for this UDP socket.
Port getLocalPort ()
 Return the local UDP port this socket is bound to.
std::string getLocalSocketAddress (bool convertIPv4Mapped)
 Return the local endpoint as a single "ip:port" string.
std::string getRemoteIp (bool convertIPv4Mapped) const
 Return the remote peer IP address for this socket.
Port getRemotePort () const
 Return the remote peer UDP port for this socket.
std::string getRemoteSocketAddress (bool convertIPv4Mapped) const
 Return the remote endpoint as a single "ip:port" string.
void write (std::string_view message) const
 Send one UDP datagram to the currently connected peer (no pre-wait).
template<typename T>
void write (const T &value) const
 Send one UDP datagram whose payload is the raw object representation of value.
void write (std::span< const std::byte > data) const
 Send one UDP datagram to the connected peer from a raw byte span (no pre-wait).
void writeAll (std::string_view message) const
 Send one UDP datagram to the connected peer, waiting indefinitely for writability.
template<typename T>
void writePrefixed (const std::string_view payload) const
 Send a length-prefixed UDP datagram to the connected peer from text bytes (no pre-wait).
template<typename T>
void writePrefixed (const std::span< const std::byte > payload) const
 Send a length-prefixed UDP datagram to the connected peer from a byte span (no pre-wait).
template<typename T>
void writePrefixedTo (const std::string_view host, const Port port, const std::string_view payload) const
 Send a length-prefixed UDP datagram to (host, port) from text bytes (unconnected path).
template<typename T>
void writePrefixedTo (const std::string_view host, const Port port, const std::span< const std::byte > payload) const
 Send a length-prefixed UDP datagram to (host, port) from a byte span (unconnected path).
void writev (std::span< const std::string_view > buffers) const
 Send one UDP datagram to the connected peer by concatenating multiple fragments (no pre-wait).
void writevAll (std::span< const std::string_view > buffers) const
 Send one UDP datagram to the connected peer by concatenating multiple fragments, waiting indefinitely.
void writeFrom (const void *data, std::size_t len) const
 Send one UDP datagram to the connected peer from a raw memory buffer (no pre-wait).
void writeWithTimeout (std::string_view data, int timeoutMillis) const
 Send one UDP datagram to the connected peer, waiting up to timeoutMillis for writability.
void write (const DatagramPacket &packet)
 Send one UDP datagram using a packet’s buffer and optional explicit destination.
void writeTo (std::string_view host, Port port, std::string_view message)
 Send one unconnected UDP datagram to (host, port) from text bytes (no pre-wait).
void writeTo (std::string_view host, Port port, std::span< const std::byte > data)
 Send one unconnected UDP datagram to (host, port) from a raw byte span (no pre-wait).
template<typename T>
void writeTo (const std::string_view host, const Port port, const T &value) const
 Send one unconnected UDP datagram to (host, port) containing the raw bytes of value.
DatagramReadResult read (DatagramPacket &packet, const DatagramReadOptions &opts) const
 Read one UDP datagram into a DatagramPacket with optional growth/shrink and strict truncation policy.
DatagramReadResult readInto (void *buffer, std::size_t len, const DatagramReadOptions &opts={}) const
 Read one UDP datagram into a caller-provided buffer with explicit truncation policy.
DatagramReadResult readInto (std::span< char > out, const DatagramReadOptions &opts={}) const
 Read one UDP datagram into a caller-provided span (zero allocation) with explicit truncation policy.
template<typename T, std::enable_if_t< detail::is_dynamic_buffer_v< T >, int > = 0>
read (const DatagramReadOptions &opts={}, std::size_t minCapacity=DefaultDatagramReceiveSize) const
 Read one UDP datagram into a dynamically resizable, contiguous byte container (zero-copy into caller storage).
template<typename T, std::enable_if_t< detail::is_fixed_buffer_v< T >, int > = 0>
read (const DatagramReadOptions &opts={}) const
 Read one UDP datagram into a fixed-size, contiguous byte container (zero allocation).
template<typename T>
DatagramReadResult readFrom (T &buffer, std::string *senderAddr, Port *senderPort, const DatagramReadOptions &opts) const
 Read one UDP datagram into a caller-provided byte container and optionally return the sender address/port.
DatagramReadResult readExact (void *buffer, std::size_t exactLen, const ReadExactOptions &opts={}) const
 Receive exactly exactLen bytes from a single UDP datagram into buffer, with strict policy control.
DatagramReadResult readExact (std::span< char > out, const ReadExactOptions &opts={}) const
 Span overload of readExact(...) (derives exactLen from out.size()).
template<typename T>
DatagramReadResult readExact (T &buffer, const std::size_t exactLen, const ReadExactOptions &opts={}) const
 Receive exactly exactLen bytes from a single UDP datagram into a contiguous byte container.
std::size_t readAtMost (std::span< char > out, const DatagramReadOptions &opts={}) const
 Read up to out.size() bytes from the next UDP datagram into a caller-provided buffer (no allocation).
std::string readAtMost (std::size_t n) const
 Read up to n bytes from the next UDP datagram and return them as a newly allocated string.
std::string readAvailable () const
 Receive the next UDP datagram and return its payload as a string, attempting to avoid truncation.
std::size_t readAvailable (std::span< char > out, const DatagramReadOptions &opts={}) const
 Receive the entire next UDP datagram into a caller-provided buffer, with explicit truncation policy.
std::size_t readIntoExact (void *buffer, std::size_t len) const
 Strict exact-length UDP receive into a caller-provided buffer (single datagram).
std::string readAtMostWithTimeout (std::size_t n, int timeoutMillis) const
 Read up to n bytes from the next UDP datagram, waiting up to timeoutMillis for data.
template<typename T, std::enable_if_t< std::is_integral_v< T > &&std::is_unsigned_v< T > &&std::is_trivially_copyable_v< T >, int > = 0>
std::string readPrefixed (std::size_t maxPayloadLen=MaxDatagramPayloadSafe, const std::endian prefixEndian=std::endian::big) const
 Read a length-prefixed UDP datagram and return the payload (prefix type T).
void discard (const DatagramReadOptions &opts={}) const
 Discard the next UDP datagram without copying it out.
void discardExact (std::size_t n, const DatagramReadOptions &opts={}) const
 Discard the next UDP datagram only if its payload size is exactly n bytes.
DatagramReadResult readv (std::span< BufferView > buffers, const DatagramReadOptions &opts={}) const
 Scatter-gather receive: read one UDP datagram into multiple non-contiguous buffers.
DatagramReadResult readvAll (std::span< BufferView > buffers, const DatagramReadOptions &opts={}) const
 Scatter-gather receive that guarantees the entire next datagram fits the provided buffers.
std::size_t readvAllBytes (std::span< BufferView > buffers, const DatagramReadOptions &opts={}) const
 Back-compat convenience returning only the number of bytes copied.
DatagramReadResult readvAtMostWithTimeout (std::span< BufferView > buffers, int timeoutMillis, const DatagramReadOptions &opts={}) const
 Scatter-gather, best-effort read of the next datagram with a per-call timeout.
std::size_t readvAtMostWithTimeout (std::span< BufferView > buffers, int timeoutMillis) const
 Convenience wrapper returning only the number of bytes read.
DatagramReadResult readvAllWithTotalTimeout (std::span< BufferView > buffers, int totalTimeoutMillis, const DatagramReadOptions &opts={}) const
 Scatter-gather, strict no-truncation receive with a per-call total timeout.
std::size_t readvAllWithTotalTimeoutBytes (std::span< BufferView > buffers, int totalTimeoutMillis, const DatagramReadOptions &opts={}) const
 Convenience wrapper returning only the number of bytes copied.
DatagramReadResult peek (DatagramPacket &packet, bool allowResize=true, const DatagramReadOptions &opts={}) const
 Peek at the next UDP datagram without consuming it (single receive with MSG_PEEK).
bool hasPendingData (int timeoutMillis) const
 Check if the socket is readable within a timeout (no data is consumed).
std::optional< int > getMTU () const
 Retrieves the Maximum Transmission Unit (MTU) of the local interface associated with the socket.
void waitReady (Direction dir, int timeoutMillis) const
 Block until the socket is ready for I/O or a timeout occurs.
void setInternalBufferSize (std::size_t newLen)
 Sets the size of the internal buffer used for string-based UDP receive operations.
void close ()
 Closes the datagram socket and releases its underlying system resources.
bool isValid () const noexcept
 Checks whether the datagram socket is valid and ready for use.
bool isClosed () const noexcept
 Checks whether the datagram socket has been closed or is otherwise invalid.
std::optional< std::pair< sockaddr_storage, socklen_t > > getLastPeerSockAddr () const
 Retrieves the raw socket address of the last known remote peer.
Public Member Functions inherited from jsocketpp::SocketOptions
 SocketOptions ()=delete
 Default constructor (deleted) for SocketOptions base class.
 SocketOptions (const SOCKET sock) noexcept
 Initializes the socket option interface with a specific socket descriptor.
virtual ~SocketOptions ()=default
 Virtual destructor for safe polymorphic destruction.
 SocketOptions (const SocketOptions &)=delete
 Copy constructor (deleted) for SocketOptions.
 SocketOptions (SocketOptions &&) noexcept=default
 Move constructor for SocketOptions.
SocketOptionsoperator= (const SocketOptions &)=delete
 Copy assignment operator (deleted) for SocketOptions.
SocketOptionsoperator= (SocketOptions &&) noexcept=default
 Move assignment operator for SocketOptions.
SOCKET getSocketFd () const noexcept
 Retrieves the native socket handle (file descriptor or OS-level handle).
void setOption (int level, int optName, int value)
 Sets a low-level socket option on the underlying socket.
void setOption (int level, int optName, const void *value, socklen_t len)
 Sets a low-level socket option using a structured or binary value.
int getOption (int level, int optName) const
 Retrieves the current value of a low-level socket option.
void getOption (int level, int optName, void *result, socklen_t *len) const
 Retrieves a socket option into a structured or binary buffer.
void setReuseAddress (bool on)
 Enables or disables the SO_REUSEADDR socket option.
bool getReuseAddress () const
 Queries whether the socket is currently configured to allow address reuse.
void setReceiveBufferSize (std::size_t size)
 Sets the socket's receive buffer size (SO_RCVBUF).
int getReceiveBufferSize () const
 Retrieves the current receive buffer size (SO_RCVBUF) of the socket.
void setSendBufferSize (std::size_t size)
 Sets the socket's send buffer size (SO_SNDBUF).
int getSendBufferSize () const
 Retrieves the current send buffer size (SO_SNDBUF) of the socket.
void setSoLinger (bool enable, int seconds)
 Configures the socket's linger behavior (SO_LINGER) during close.
std::pair< bool, int > getSoLinger () const
 Retrieves the current SO_LINGER configuration of the socket.
void setKeepAlive (bool on)
 Enables or disables TCP-level keepalive behavior on the socket (SO_KEEPALIVE).
bool getKeepAlive () const
 Checks whether TCP-level keepalive (SO_KEEPALIVE) is currently enabled.
void setSoRecvTimeout (int millis)
 Sets the socket receive timeout (SO_RCVTIMEO) in milliseconds.
void setSoSendTimeout (int millis)
 Sets the socket send timeout (SO_SNDTIMEO) in milliseconds.
int getSoRecvTimeout () const
 Retrieves the socket receive timeout (SO_RCVTIMEO) in milliseconds.
int getSoSendTimeout () const
 Retrieves the socket send timeout (SO_SNDTIMEO) in milliseconds.
void setNonBlocking (bool nonBlocking)
 Enables or disables non-blocking mode on the socket.
bool getNonBlocking () const
 Queries whether the socket is currently in non-blocking mode.
void setTcpNoDelay (bool on)
 Enables or disables Nagle’s algorithm (TCP_NODELAY) on TCP sockets.
bool getTcpNoDelay () const
 Queries whether Nagle's algorithm (TCP_NODELAY) is currently disabled.
void setBroadcast (bool on)
 Enables or disables the ability to send UDP broadcast messages.
bool getBroadcast () const
 Checks whether the socket is currently allowed to send broadcast messages.
void setIPv6Only (bool enable)
 Enables or disables IPV6_V6ONLY mode for IPv6-capable sockets.
bool getIPv6Only () const
 Queries whether the IPV6_V6ONLY option is enabled on this socket.
void setReusePort (const bool enable)
 Enables or disables the SO_REUSEPORT socket option.
bool getReusePort () const
 Checks whether the SO_REUSEPORT option is currently enabled on the socket.
void setMulticastTTL (int ttl)
 Set the default multicast hop limit / TTL for this socket.
int getMulticastTTL () const
 Get the socket’s default multicast hop limit / TTL.
void setMulticastLoopback (bool enable)
 Enable or disable multicast loopback for this socket.
bool getMulticastLoopback () const
 Read the socket’s multicast loopback flag.
void setMulticastInterfaceIPv4 (in_addr addr)
 Select the outgoing IPv4 interface for multicast.
void setMulticastInterfaceIPv6 (unsigned int ifindex)
 Select the outgoing IPv6 interface for multicast.
void joinGroupIPv4 (in_addr group, in_addr iface)
 Join an IPv4 any-source multicast (ASM) group on a specific interface.
void leaveGroupIPv4 (in_addr group, in_addr iface)
 Leave a previously joined IPv4 multicast group on a specific interface.
void joinGroupIPv6 (in6_addr group, unsigned int ifindex)
 Join an IPv6 any-source multicast (ASM) group on a specific interface index.
void leaveGroupIPv6 (in6_addr group, unsigned int ifindex)
 Leave a previously joined IPv6 multicast group on a specific interface index.

Protected Member Functions

std::size_t readIntoBuffer (char *buf, std::size_t len, DatagramReceiveMode mode, int recvFlags, sockaddr_storage *outSrc, socklen_t *outSrcLen, std::size_t *outDatagramSz, bool *outTruncated) const
 Low-level, single-recv primitive that copies one UDP datagram into a caller buffer.
void cleanup ()
 Internal helper that releases socket resources and resets all internal state.
void cleanupAndThrow (int errorCode)
 Releases all socket resources and throws a SocketException with the given error code.
void cleanupAndRethrow ()
 Cleans up the datagram socket and rethrows the currently active exception.
std::size_t chooseReceiveSize () const
 Decide how many bytes to attempt to receive for the next UDP datagram.
void rememberRemote (const sockaddr_storage &src, const socklen_t len) const noexcept
 Remember the last remote peer after an unconnected receive.
void enforceSendCapConnected (const std::size_t payloadSize) const
 Enforce UDP payload size limits for connected datagram sends.
void sendUnconnectedTo (std::string_view host, Port port, const void *data, std::size_t len)
 Resolve and send one unconnected UDP datagram to the first compatible destination.
template<typename T>
void sendPrefixedConnected (const std::span< const std::byte > payload) const
 Build and send a length-prefixed UDP datagram to the connected peer (no pre-wait).
template<typename T>
void sendPrefixedUnconnected (const std::string_view host, const Port port, const std::span< const std::byte > payload)
 Build and send a length-prefixed UDP datagram to (host, port) on the unconnected path.
void cacheLocalEndpoint () noexcept
 Cache the actual local endpoint assigned by the OS.
bool tryGetRemoteSockaddr (sockaddr_storage &out, socklen_t &outLen) const
 Retrieve the remote endpoint sockaddr for this socket, if available.
Protected Member Functions inherited from jsocketpp::SocketOptions
void setSocketFd (const SOCKET sock) noexcept
 Updates the socket descriptor used by this object.
virtual bool isPassiveSocket () const noexcept
 Indicates whether the socket behaves as a passive (listening) socket.

Static Protected Member Functions

static void throwSizeMismatch (const std::size_t expected, const std::size_t actual, const bool isProbedKnown)
 Throw a descriptive exception when a UDP datagram’s size differs from what was expected.
static std::span< const std::byte > asBytes (const std::string_view sv) noexcept
 View a textual buffer as raw bytes without copying.
template<typename T>
static std::array< std::byte, sizeof(T)> encodeLengthPrefixBE (std::size_t n)
 Encode a length value into a fixed-size, big-endian (network-order) byte array.
Static Protected Member Functions inherited from jsocketpp::SocketOptions
static bool is_ipv4_multicast (const in_addr v4)
 Test whether an IPv4 address is in the multicast range (224.0.0.0/4).
static bool is_ipv6_multicast (const in6_addr &v6)
 Test whether an IPv6 address is in the multicast range (ff00::/8).
static int detectFamily (SOCKET fd)
 Determine the address family (AF_INET or AF_INET6) of a socket.

Private Attributes

sockaddr_storage _remoteAddr {}
 Storage for the address of the most recent sender (used in unconnected mode).
socklen_t _remoteAddrLen
 Length of the valid address data in _remoteAddr (0 if none received yet).
std::atomic_bool _haveRemoteAddr = false
sockaddr_storage _localAddr {}
 Cached local socket address (set by bind()/UDP connect() via getsockname()).
socklen_t _localAddrLen = 0
 Size in bytes of the cached local address stored in _localAddr.
std::atomic_bool _haveLocalAddr
 True if _localAddr/_localAddrLen contain a valid endpoint; reset on close().
std::vector< char > _internalBuffer
 Internal buffer for read operations.
Port _port
 Port number the socket is bound to (if applicable).
bool _isBound = false
 True if the socket is bound to an address.
bool _isConnected = false
 True if the socket is connected to a remote host.

Detailed Description

Cross-platform UDP socket class with Java-style interface.

The DatagramSocket class provides a convenient, cross-platform abstraction for sending and receiving UDP datagrams, inspired by the Java API. It supports both IPv4 and IPv6, and works on Windows and Linux.

What is UDP?

UDP (User Datagram Protocol) is a lightweight, connectionless protocol for sending packets over the network. Unlike TCP, UDP does not guarantee delivery, ordering, or duplicate protection—packets may be lost, arrive out of order, or duplicated. However, UDP is fast and simple, and widely used for real-time applications (such as online games, video streaming, and VoIP).

Key Features

  • Connectionless and connected modes: You can send datagrams to any address/port, or "connect" the socket to a default destination for simpler sending/receiving.
  • Custom buffer size: Easily set the size of the internal buffer for large or small datagrams.
  • Broadcast support: Easily enable broadcast packets.
  • Timeouts and non-blocking mode: Set timeouts and switch between blocking/non-blocking operations.
  • Java-style interface: Familiar to those who have used Java networking.

Example: Simple UDP Echo Server and Client

// --- Server ---
#include <iostream>
int main() {
jsocketpp::DatagramSocket server(12345); // Bind to port 12345
while (true) {
size_t received = server.read(packet);
std::cout << "Received: " << std::string(packet.buffer.begin(), packet.buffer.end())
<< " from " << packet.address << ":" << packet.port << std::endl;
// Echo back
server.write(packet);
}
}
UDP datagram socket abstraction for jsocketpp.
Represents a UDP datagram packet, encapsulating both payload and addressing information.
Definition DatagramPacket.hpp:48
Cross-platform UDP socket class with Java-style interface.
Definition DatagramSocket.hpp:484
int main()
Definition client.cpp:89
// --- Client ---
#include <iostream>
int main() {
std::string message = "Hello UDP!";
client.write(message, "127.0.0.1", 12345); // Send to server
jsocketpp::DatagramPacket response(2048);
client.read(response);
std::cout << "Server replied: " << std::string(response.buffer.begin(), response.buffer.end()) << std::endl;
}
void write(std::string_view message) const
Send one UDP datagram to the currently connected peer (no pre-wait).
Definition DatagramSocket.cpp:458
DatagramReadResult read(DatagramPacket &packet, const DatagramReadOptions &opts) const
Read one UDP datagram into a DatagramPacket with optional growth/shrink and strict truncation policy.
Definition DatagramSocket.cpp:862

Notes

  • Not thread-safe. Use each DatagramSocket instance from only one thread at a time.
  • Use the DatagramPacket class to store both the data and the address/port of the sender/receiver.
  • To receive the sender’s address and port, use the read(DatagramPacket&) method.
See also
jsocketpp::DatagramPacket
jsocketpp::SocketException

Member Function Documentation

◆ readAtMost()

std::string DatagramSocket::readAtMost ( std::size_t n) const
nodiscard

Read up to n bytes from the next UDP datagram and return them as a newly allocated string.

Performs exactly one receive operation (single recvfrom/recv) with best-effort, at-most semantics:

  • If the incoming datagram is smaller than n, the returned string’s size equals the datagram size.
  • If the datagram is larger than n, only the first n bytes are returned and the remainder is discarded (standard UDP truncation semantics).

This convenience overload enforces DatagramReceiveMode::NoPreflight (no size preflight, no extra syscalls). It works for both connected and unconnected sockets. On unconnected sockets, the internally tracked “last remote” endpoint is updated to the sender of the received datagram.

Blocking/timeout behavior:

  • If the socket is blocking and no datagram is available, the call blocks until one arrives or a configured receive timeout elapses.
  • If a receive timeout applies and expires before any datagram is received, a SocketTimeoutException is thrown.
  • If the socket is non-blocking and no data is available, behavior follows the lower-level readInto(...) policy (typically throwing on would-block).
Parameters
[in]nMaximum number of bytes to read (and to appear in the returned string). If 0, returns an empty string.
Returns
The payload bytes read (size ≤ n). Marked [[nodiscard]] to help prevent accidental loss of data.
Exceptions
SocketExceptionIf the socket is not open, not readable, or on other OS-level errors.
SocketTimeoutExceptionIf a configured receive timeout elapses before any datagram is received.
Precondition
The socket has been successfully created/opened.
Postcondition
On success, the returned string contains the bytes received; for unconnected sockets, the internal “last remote” is updated to the sender of the received datagram.
Note
This overload allocates and may shrink the string after receive. For zero-allocation reads, prefer readAtMost(std::span<char>, const DatagramReadOptions&).
Warning
If n is smaller than the incoming datagram, the remainder of that datagram is dropped.
Example
// Read up to 1400 bytes from the next datagram
std::string payload = sock.readAtMost(1400);
// use payload...
See also
readAtMost(std::span<char>, const DatagramReadOptions&) for a span-first, zero-allocation overload.
readInto(void*, std::size_t, const DatagramReadOptions&) for the lower-level primitive.
read(DatagramPacket&, const DatagramReadOptions&) when you also need the sender address.

◆ rememberRemote()

void jsocketpp::DatagramSocket::rememberRemote ( const sockaddr_storage & src,
const socklen_t len ) const
inlineprotectednoexcept

Remember the last remote peer after an unconnected receive.

Copies src into @_remoteAddr and sets @_remoteAddrLen to len. This updates the values returned by getRemoteIp(), getRemotePort(), and getRemoteSocketAddress() to reflect the most recent sender on unconnected sockets.

Parameters
[in]srcSender address as returned by recvfrom().
[in]lenLength of src.
Note
Callers should only invoke this after a successful receive with recvfrom().
Since
1.0

Member Data Documentation

◆ _haveLocalAddr

std::atomic_bool jsocketpp::DatagramSocket::_haveLocalAddr
private
Initial value:
=
false

True if _localAddr/_localAddrLen contain a valid endpoint; reset on close().

◆ _haveRemoteAddr

std::atomic_bool jsocketpp::DatagramSocket::_haveRemoteAddr = false
mutableprivate

◆ _internalBuffer

std::vector<char> jsocketpp::DatagramSocket::_internalBuffer
private

Internal buffer for read operations.

◆ _isBound

bool jsocketpp::DatagramSocket::_isBound = false
private

True if the socket is bound to an address.

◆ _isConnected

bool jsocketpp::DatagramSocket::_isConnected = false
private

True if the socket is connected to a remote host.

◆ _localAddr

sockaddr_storage jsocketpp::DatagramSocket::_localAddr {}
private

Cached local socket address (set by bind()/UDP connect() via getsockname()).

◆ _localAddrLen

socklen_t jsocketpp::DatagramSocket::_localAddrLen = 0
private

Size in bytes of the cached local address stored in _localAddr.

◆ _port

Port jsocketpp::DatagramSocket::_port
private

Port number the socket is bound to (if applicable).

◆ _remoteAddr

sockaddr_storage jsocketpp::DatagramSocket::_remoteAddr {}
mutableprivate

Storage for the address of the most recent sender (used in unconnected mode).

◆ _remoteAddrLen

socklen_t jsocketpp::DatagramSocket::_remoteAddrLen
mutableprivate
Initial value:
=
0

Length of the valid address data in _remoteAddr (0 if none received yet).


The documentation for this class was generated from the following files: