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:

Public Member Functions

 DatagramSocket (Port port, std::size_t bufferSize=2048)
 Constructs a UDP socket optionally bound to a local port.
 DatagramSocket (std::string_view host, Port port, std::size_t bufferSize=2048)
 Construct a datagram socket to a remote host and port.
 ~DatagramSocket () noexcept
 Destructor. Closes the socket and frees resources.
 DatagramSocket (const DatagramSocket &)=delete
 Copy constructor (deleted).
DatagramSocketoperator= (const DatagramSocket &)=delete
 Copy assignment operator (deleted).
 DatagramSocket (DatagramSocket &&other) noexcept
 Move constructor.
DatagramSocketoperator= (DatagramSocket &&other) noexcept
 Move assignment operator.
void bind () const
 Bind the datagram socket to the configured port set in the constructor.
void connect (int timeoutMillis=-1)
 Connects the datagram socket to the remote host and port with optional timeout handling.
size_t write (const DatagramPacket &packet) const
 Write data to a remote host using a DatagramPacket.
size_t write (std::string_view message) const
 Write data to the socket (connected UDP) from a string_view.
size_t write (std::string_view message, std::string_view host, Port port) const
 Send a datagram to a specific host and port (connectionless UDP).
size_t read (DatagramPacket &packet, bool resizeBuffer=true) const
 Receives a UDP datagram and fills the provided DatagramPacket.
template<typename T>
read ()
 Read a trivially copyable type from the socket (connected UDP).
template<typename T>
recvFrom (std::string *senderAddr, Port *senderPort)
 Receive a datagram into a trivially copyable type.
void close ()
 Close the datagram socket.
void setNonBlocking (bool nonBlocking) const
 Set the socket to non-blocking or blocking mode.
void setTimeout (int millis) const
 Sets the socket's receive timeout.
void setOption (int level, int optName, int value) const
 Set a socket option (integer value).
int getOption (int level, int optName) const
 Get a socket option (integer value).
std::string getLocalSocketAddress () const
 Get the local socket's address as a string (ip:port).
bool isValid () const
 Check if the datagram socket is valid (open).
bool isConnected () const
 Check if the datagram socket is connected to a remote host.
void enableBroadcast (bool enable) const
 Enable or disable the ability to send broadcast packets.

Protected Member Functions

void cleanupAndThrow (int errorCode)
 Cleans up datagram socket resources and throws a SocketException.

Protected Attributes

SOCKET _sockFd = INVALID_SOCKET
 Underlying socket file descriptor.
addrinfo * _addrInfoPtr = nullptr
 Address info pointer for bind/connect.
addrinfo * _selectedAddrInfo = nullptr
 Selected address info for connection.

Private Attributes

sockaddr_storage _localAddr {}
 Local address structure.
socklen_t _localAddrLen = 0
 Length of local address.
std::vector< char > _buffer
 Internal buffer for read operations.
Port _port
 Port number the socket is bound to (if applicable).
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:81
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;
}
size_t read(DatagramPacket &packet, bool resizeBuffer=true) const
Receives a UDP datagram and fills the provided DatagramPacket.
Definition DatagramSocket.cpp:343
size_t write(const DatagramPacket &packet) const
Write data to a remote host using a DatagramPacket.
Definition DatagramSocket.cpp:232

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

Constructor & Destructor Documentation

◆ DatagramSocket() [1/4]

DatagramSocket::DatagramSocket ( Port port,
std::size_t bufferSize = 2048 )
explicit

Constructs a UDP socket optionally bound to a local port.

Parameters
portThe local UDP port to bind to (0 means any available port). Common scenarios:
  • Server: Use specific port (e.g., 8888) that clients know
  • Client: Use 0 to get any available port
bufferSizeSize of the receive buffer in bytes (default: 2048). Choose based on your expected maximum datagram size:
  • IPv4: Max 65,507 bytes
  • IPv6: Max 65,527 bytes
  • Typical values: 1024-8192 bytes
Exceptions
SocketExceptionif socket creation or binding fails

◆ DatagramSocket() [2/4]

DatagramSocket::DatagramSocket ( std::string_view host,
Port port,
std::size_t bufferSize = 2048 )

Construct a datagram socket to a remote host and port.

Parameters
hostHostname or IP address to connect to.
portUDP port number.
bufferSizeSize of the internal receive buffer (default: 2048).
Exceptions
SocketExceptionon failure.

◆ ~DatagramSocket()

DatagramSocket::~DatagramSocket ( )
noexcept

Destructor. Closes the socket and frees resources.

◆ DatagramSocket() [3/4]

jsocketpp::DatagramSocket::DatagramSocket ( const DatagramSocket & )
delete

Copy constructor (deleted).

◆ DatagramSocket() [4/4]

jsocketpp::DatagramSocket::DatagramSocket ( DatagramSocket && other)
inlinenoexcept

Move constructor.

Transfers ownership of the socket and resources from another DatagramSocket. The moved-from object is left in a valid but unspecified state.

Member Function Documentation

◆ bind()

void DatagramSocket::bind ( ) const

Bind the datagram socket to the configured port set in the constructor.

Exceptions
SocketExceptionon error.

◆ cleanupAndThrow()

void DatagramSocket::cleanupAndThrow ( int errorCode)
protected

Cleans up datagram socket resources and throws a SocketException.

This method performs cleanup of the address information structures (_addrInfoPtr) and throws a SocketException with the provided error code. It's typically called when an error occurs during socket initialization or configuration.

Parameters
errorCodeThe error code to include in the thrown exception
Exceptions
SocketExceptionAlways throws with the provided error code and corresponding message

◆ close()

void DatagramSocket::close ( )

Close the datagram socket.

◆ connect()

void DatagramSocket::connect ( int timeoutMillis = -1)

Connects the datagram socket to the remote host and port with optional timeout handling.

This function binds the datagram socket to a specific remote destination (host and port) for sending subsequent datagrams. Although UDP is connectionless, calling connect() on a datagram socket allows the socket to send datagrams to a specific destination without needing to specify the address each time.

The connection process works as follows:

  • In non-blocking mode, the connection attempt proceeds immediately. If the connection cannot be completed right away, it will return EINPROGRESS (or WSAEINPROGRESS on Windows), indicating that the connection is still in progress.
  • select() is used to wait for the socket to be ready for communication within the specified timeout.
  • If no timeout is specified (i.e., timeoutMillis < 0), the socket connects in blocking mode, which will block until either the connection completes or an error occurs.
  • If the connection fails or times out, an exception is thrown with the relevant error code and message.

This function is cross-platform and works on both Windows and Linux systems.

Parameters
timeoutMillisThe maximum time to wait for the connection to be established, in milliseconds. If set to a negative value, the connection will be attempted in blocking mode (no timeout). If set to a non-negative value, the connection will be attempted in non-blocking mode, and select() will be used to wait for the connection to complete within the specified timeout.
Exceptions
SocketExceptionIf the connection fails, times out, or if there is an error during the connection attempt. The exception will contain the error code and message describing the failure.

◆ enableBroadcast()

void DatagramSocket::enableBroadcast ( bool enable) const

Enable or disable the ability to send broadcast packets.

Parameters
enableSet to true to enable broadcast, false to disable.
Exceptions
SocketExceptionon error.

◆ getLocalSocketAddress()

std::string DatagramSocket::getLocalSocketAddress ( ) const

Get the local socket's address as a string (ip:port).

Returns
String representation of the local address.

◆ getOption()

int DatagramSocket::getOption ( int level,
int optName ) const
nodiscard

Get a socket option (integer value).

Parameters
levelOption level (e.g., SOL_SOCKET).
optNameOption name (e.g., SO_BROADCAST).
Returns
Integer value of the option.
Exceptions
SocketExceptionon error.

◆ isConnected()

bool jsocketpp::DatagramSocket::isConnected ( ) const
inlinenodiscard

Check if the datagram socket is connected to a remote host.

For UDP sockets, "connected" means that the socket has been associated with a specific remote address using connect(). This doesn't establish a true connection like TCP, but allows send() and recv() to be used instead of sendto() and recvfrom().

Returns
true if the socket is connected to a remote host, false otherwise.

◆ isValid()

bool jsocketpp::DatagramSocket::isValid ( ) const
inlinenodiscard

Check if the datagram socket is valid (open).

Returns
true if valid, false otherwise.

◆ operator=() [1/2]

DatagramSocket & jsocketpp::DatagramSocket::operator= ( const DatagramSocket & )
delete

Copy assignment operator (deleted).

◆ operator=() [2/2]

DatagramSocket & jsocketpp::DatagramSocket::operator= ( DatagramSocket && other)
inlinenoexcept

Move assignment operator.

Releases any owned resources and transfers ownership from another DatagramSocket.

◆ read() [1/2]

template<typename T>
T jsocketpp::DatagramSocket::read ( )
inline

Read a trivially copyable type from the socket (connected UDP).

Template Parameters
TType to read (must be trivially copyable).
Returns
Value of type T received from the socket.
Exceptions
SocketExceptionon error or disconnect.

◆ read() [2/2]

size_t DatagramSocket::read ( DatagramPacket & packet,
bool resizeBuffer = true ) const
nodiscard

Receives a UDP datagram and fills the provided DatagramPacket.

Receives a datagram into the packet's buffer, and sets the sender's address and port fields. The buffer should be preallocated to the maximum expected datagram size.

Parameters
packetDatagramPacket object to receive into (buffer should be pre-sized).
resizeBufferIf true (default), resizes packet.buffer to the number of bytes received. If false, leaves buffer size unchanged (only the initial part of the buffer is valid)
Returns
Number of bytes received.
Exceptions
SocketExceptionon error.

◆ recvFrom()

template<typename T>
T jsocketpp::DatagramSocket::recvFrom ( std::string * senderAddr,
Port * senderPort )
inline

Receive a datagram into a trivially copyable type.

Template Parameters
TThe type to receive.
Parameters
senderAddr[out] String to store sender's address.
senderPort[out] Variable to store sender's port.
Returns
The received value of type T.
Exceptions
SocketExceptionon error.

◆ setNonBlocking()

void DatagramSocket::setNonBlocking ( bool nonBlocking) const

Set the socket to non-blocking or blocking mode.

Parameters
nonBlockingtrue for non-blocking, false for blocking.
Exceptions
SocketExceptionon error.

◆ setOption()

void DatagramSocket::setOption ( int level,
int optName,
int value ) const

Set a socket option (integer value).

Parameters
levelOption level (e.g., SOL_SOCKET).
optNameOption name (e.g., SO_BROADCAST).
valueInteger value to set for the option.
Exceptions
SocketExceptionon error.

◆ setTimeout()

void DatagramSocket::setTimeout ( int millis) const

Sets the socket's receive timeout.

Parameters
millisTimeout in milliseconds:
  • 0: No timeout (blocking mode)
  • >0: Wait up to specified milliseconds Common values:
  • 1000 (1 second): Quick response time
  • 5000 (5 seconds): Balance between responsiveness and reliability
  • 30000 (30 seconds): Long-running operations
Exceptions
SocketExceptionif setting timeout fails

◆ write() [1/3]

size_t DatagramSocket::write ( const DatagramPacket & packet) const
nodiscard

Write data to a remote host using a DatagramPacket.

Sends the data contained in the packet's buffer to the address and port specified in the packet. Can be used in both connected and connectionless modes.

Parameters
packetDatagramPacket containing the data to send and destination info.
Returns
Number of bytes sent.
Exceptions
SocketExceptionon error.

◆ write() [2/3]

size_t DatagramSocket::write ( std::string_view message) const
nodiscard

Write data to the socket (connected UDP) from a string_view.

Parameters
messageThe data to send.
Returns
Number of bytes sent.
Exceptions
SocketExceptionon error.

◆ write() [3/3]

size_t DatagramSocket::write ( std::string_view message,
std::string_view host,
Port port ) const
nodiscard

Send a datagram to a specific host and port (connectionless UDP).

Parameters
messageThe message to send.
hostThe destination hostname or IP.
portThe destination port.
Returns
Number of bytes sent.
Exceptions
SocketExceptionon error.

Member Data Documentation

◆ _addrInfoPtr

addrinfo* jsocketpp::DatagramSocket::_addrInfoPtr = nullptr
protected

Address info pointer for bind/connect.

◆ _buffer

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

Internal buffer for read operations.

◆ _isConnected

bool jsocketpp::DatagramSocket::_isConnected = false
private

True if the socket is connected to a remote host.

◆ _localAddr

sockaddr_storage jsocketpp::DatagramSocket::_localAddr {}
private

Local address structure.

◆ _localAddrLen

socklen_t jsocketpp::DatagramSocket::_localAddrLen = 0
mutableprivate

Length of local address.

◆ _port

Port jsocketpp::DatagramSocket::_port
private

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

◆ _selectedAddrInfo

addrinfo* jsocketpp::DatagramSocket::_selectedAddrInfo = nullptr
protected

Selected address info for connection.

◆ _sockFd

SOCKET jsocketpp::DatagramSocket::_sockFd = INVALID_SOCKET
protected

Underlying socket file descriptor.


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