libpromeki main
PROfessional MEdia toolKIt
 
Loading...
Searching...
No Matches
UdpSocket Class Reference

Datagram-oriented UDP socket with multicast support. More...

#include <udpsocket.h>

Inheritance diagram for UdpSocket:
Collaboration diagram for UdpSocket:

Public Member Functions

 UdpSocket (ObjectBase *parent=nullptr)
 Constructs a UdpSocket.
 
 ~UdpSocket () override
 Destructor.
 
Error open (OpenMode mode) override
 Opens the socket.
 
Error openIpv6 (OpenMode mode)
 Opens the socket for IPv6 operation.
 
Error close () override
 Closes the socket.
 
bool isOpen () const override
 Returns true if the socket is open.
 
int64_t read (void *data, int64_t maxSize) override
 Reads data from a connected UDP socket.
 
int64_t write (const void *data, int64_t maxSize) override
 Writes data to a connected UDP socket.
 
int64_t bytesAvailable () const override
 Returns the number of bytes available for reading.
 
ssize_t writeDatagram (const void *data, size_t size, const SocketAddress &dest)
 Sends a datagram to a specific destination.
 
ssize_t writeDatagram (const Buffer &data, const SocketAddress &dest)
 Sends a Buffer as a datagram.
 
ssize_t readDatagram (void *data, size_t maxSize, SocketAddress *sender=nullptr)
 Receives a datagram.
 
bool hasPendingDatagrams () const
 Returns true if there are pending datagrams to read.
 
ssize_t pendingDatagramSize () const
 Returns the size of the next pending datagram.
 
Error joinMulticastGroup (const SocketAddress &group)
 Joins a multicast group.
 
Error joinMulticastGroup (const SocketAddress &group, const String &iface)
 Joins a multicast group on a specific interface.
 
Error leaveMulticastGroup (const SocketAddress &group)
 Leaves a multicast group.
 
Error setMulticastTTL (int ttl)
 Sets the multicast TTL (time to live).
 
Error setMulticastLoopback (bool enable)
 Enables or disables multicast loopback.
 
Error setMulticastInterface (const String &iface)
 Sets the outgoing multicast interface.
 
Error setReuseAddress (bool enable)
 Enables or disables SO_REUSEADDR.
 
Error setDscp (uint8_t dscp)
 Sets the DSCP (Differentiated Services) value.
 
- Public Member Functions inherited from AbstractSocket
 AbstractSocket (SocketType type, ObjectBase *parent=nullptr)
 Constructs an AbstractSocket.
 
virtual ~AbstractSocket ()
 Destructor. Closes the socket if open.
 
SocketType socketType () const
 Returns the socket type.
 
SocketState state () const
 Returns the current socket state.
 
Error bind (const SocketAddress &address)
 Binds the socket to a local address.
 
Error connectToHost (const SocketAddress &address)
 Initiates a connection to a remote host.
 
void disconnectFromHost ()
 Disconnects from the remote host.
 
SocketAddress localAddress () const
 Returns the local address the socket is bound to.
 
SocketAddress peerAddress () const
 Returns the address of the connected peer.
 
Error waitForConnected (unsigned int timeoutMs=0)
 Blocks until the socket is connected or timeout.
 
int socketDescriptor () const
 Returns the raw socket file descriptor.
 
void setSocketDescriptor (int fd)
 Adopts an existing file descriptor as the socket.
 
Error setSocketOption (int level, int option, int value)
 Sets a raw socket option via setsockopt().
 
Result< int > socketOption (int level, int option) const
 Gets a raw socket option via getsockopt().
 
bool isSequential () const override
 Returns true — sockets are sequential (non-seekable).
 
 PROMEKI_SIGNAL (connected)
 Emitted when a connection is established.
 
 PROMEKI_SIGNAL (disconnected)
 Emitted when the socket is disconnected.
 
 PROMEKI_SIGNAL (stateChanged, SocketState)
 Emitted when the socket state changes.
 
- Public Member Functions inherited from IODevice
 IODevice (ObjectBase *parent=nullptr)
 Constructs an IODevice.
 
virtual ~IODevice ()
 Destructor.
 
virtual void flush ()
 Flushes any buffered output data to the underlying device.
 
virtual bool waitForReadyRead (unsigned int timeoutMs=0)
 Waits until data is available for reading or timeout.
 
virtual bool waitForBytesWritten (unsigned int timeoutMs=0)
 Waits until all pending data has been written or timeout.
 
virtual Error seek (int64_t pos)
 Seeks to the given byte offset from the beginning.
 
virtual int64_t pos () const
 Returns the current read/write position.
 
virtual Result< int64_tsize () const
 Returns the total size of the device in bytes.
 
virtual bool atEnd () const
 Returns true if the current position is at the end.
 
OpenMode openMode () const
 Returns the current open mode.
 
bool isReadable () const
 Returns true if the device is readable.
 
bool isWritable () const
 Returns true if the device is writable.
 
Error error () const
 Returns the current error state.
 
void clearError ()
 Clears the error state to Ok.
 
 PROMEKI_SIGNAL (readyRead)
 Emitted when data is available for reading.
 
 PROMEKI_SIGNAL (bytesWritten, int64_t)
 Emitted when bytes have been written.
 
 PROMEKI_SIGNAL (errorOccurred, Error)
 Emitted when an error occurs.
 
 PROMEKI_SIGNAL (aboutToClose)
 Emitted just before the device is closed.
 
- Public Member Functions inherited from ObjectBase
 ObjectBase (ObjectBase *p=nullptr)
 Default ObjectBase constructor.
 
virtual ~ObjectBase ()
 Destructor. Emits aboutToDestroy, detaches from parent, and destroys children.
 
ObjectBaseparent () const
 Returns the parent object, if one. nullptr if none.
 
void setParent (ObjectBase *p)
 Sets the parent of this object. If the object already has a parent, it will be removed as a child from the old parent and added as a child to the new one.
 
const ObjectBaseListchildList () const
 Returns a list of children of this object.
 
template<typename... Args>
int registerSlot (Slot< Args... > *slot)
 Registers a slot with this object and assigns it an ID.
 
EventLoopeventLoop () const
 Returns the EventLoop this object is affiliated with.
 
void moveToThread (EventLoop *loop)
 Changes the EventLoop affinity of this object.
 
int startTimer (unsigned int intervalMs, bool singleShot=false)
 Starts a timer on this object's EventLoop.
 
void stopTimer (int timerId)
 Stops a timer previously started with startTimer().
 
template<typename... Args>
PROMEKI_NAMESPACE_BEGIN void connect (Signal< Args... > *signal, Slot< Args... > *slot)
 

Additional Inherited Members

- Public Types inherited from AbstractSocket
enum  SocketType { TcpSocketType , UdpSocketType , RawSocketType }
 The type of socket. More...
 
enum  SocketState {
  Unconnected , Connecting , Connected , Bound ,
  Closing , Listening
}
 The current state of the socket. More...
 
- Public Types inherited from IODevice
enum  OpenMode {
  NotOpen = 0x00 , ReadOnly = 0x01 , WriteOnly = 0x02 , ReadWrite = ReadOnly | WriteOnly ,
  Append = 0x04 | WriteOnly
}
 Mode flags controlling how a device is opened. More...
 
- Public Types inherited from ObjectBase
using SlotVariantFunc = std::function< void(const VariantList &)>
 Function type for invoking a slot with a list of Variants.
 
- Static Public Member Functions inherited from ObjectBase
static const MetaInfometaInfo ()
 Returns the MetaInfo for the ObjectBase class.
 
template<typename... Args>
static void connect (Signal< Args... > *signal, Slot< Args... > *slot)
 connects a signal and slot together. This function assumes both the signal and slot exist in a ObjectBase or derived object
 
- Public Attributes inherited from ObjectBase
Signal< ObjectBase * > aboutToDestroySignal = Signal< ObjectBase * >(this, aboutToDestroySignalName)
 
- Static Public Attributes inherited from ObjectBase
static constexpr const charaboutToDestroySignalName = PROMEKI_STRINGIFY( aboutToDestroy ) "(" PROMEKI_STRINGIFY_ARGS( ObjectBase * ) ")"
 
static SignalMeta aboutToDestroySignalMeta = SignalMeta(metaInfo(), aboutToDestroySignalName)
 
- Protected Member Functions inherited from AbstractSocket
Error createSocket (int domain, int type, int protocol=0)
 Creates the underlying socket descriptor.
 
void closeSocket ()
 Closes the socket descriptor.
 
Error setNonBlocking (bool enable)
 Sets the socket to non-blocking mode.
 
void updateLocalAddress ()
 Updates the local address from the socket descriptor.
 
void setState (SocketState state)
 Sets the socket state and emits stateChanged.
 
- Protected Member Functions inherited from IODevice
void setOpenMode (OpenMode mode)
 Sets the open mode.
 
void setError (const Error &err)
 Sets the error state and emits errorOccurred.
 
- Protected Member Functions inherited from ObjectBase
ObjectBasesignalSender ()
 Returns the ObjectBase that emitted the signal currently being handled.
 
virtual void event (Event *e)
 Called by EventLoop to deliver events to this object.
 
virtual void timerEvent (TimerEvent *e)
 Called when a timer fires for this object.
 
- Protected Attributes inherited from AbstractSocket
int _fd = -1
 Socket file descriptor.
 
SocketState _state = Unconnected
 Current socket state.
 
SocketType _type
 Socket type.
 
SocketAddress _localAddress
 Local bound address.
 
SocketAddress _peerAddress
 Connected peer address.
 

Detailed Description

Datagram-oriented UDP socket with multicast support.

UdpSocket provides connectionless datagram communication over UDP. It supports unicast and multicast send/receive, including joining and leaving multicast groups with optional interface binding.

For connected-mode UDP (via connectToHost()), the standard IODevice read()/write() methods can be used. For connectionless operation, use writeDatagram()/readDatagram() with explicit destination/source addresses.

This class must only be used from the thread that created it (or moved to via moveToThread()).

Example
// Send a datagram
SocketAddress dest(Ipv4Address(239, 0, 0, 1), 5004);
sock.writeDatagram("hello", 5, dest);
// Receive a datagram
char buf[1500];
ssize_t n = sock.readDatagram(buf, sizeof(buf), &sender);
@ ReadWrite
Open for reading and writing.
Definition iodevice.h:37
IPv4 network address.
Definition ipv4address.h:51
Dynamic array container wrapping std::vector.
Definition list.h:40
Network address with port number.
Definition socketaddress.h:50
static SocketAddress any(uint16_t port)
Returns INADDR_ANY with the given port.
Definition socketaddress.h:71
Datagram-oriented UDP socket with multicast support.
Definition udpsocket.h:47

Constructor & Destructor Documentation

◆ UdpSocket()

UdpSocket::UdpSocket ( ObjectBase parent = nullptr)

Constructs a UdpSocket.

Parameters
parentThe parent object, or nullptr.

Member Function Documentation

◆ bytesAvailable()

int64_t UdpSocket::bytesAvailable ( ) const
overridevirtual

Returns the number of bytes available for reading.

Returns
Bytes available, or 0 if unknown.

Reimplemented from IODevice.

◆ close()

Error UdpSocket::close ( )
overridevirtual

Closes the socket.

Returns
Error::Ok on success, or an error on failure.

Implements IODevice.

◆ hasPendingDatagrams()

bool UdpSocket::hasPendingDatagrams ( ) const

Returns true if there are pending datagrams to read.

Returns
True if a datagram is available.

◆ isOpen()

bool UdpSocket::isOpen ( ) const
inlineoverridevirtual

Returns true if the socket is open.

Implements IODevice.

◆ joinMulticastGroup() [1/2]

Error UdpSocket::joinMulticastGroup ( const SocketAddress group)

Joins a multicast group.

Parameters
groupThe multicast group address and port.
Returns
Error::Ok on success, or an error on failure.

◆ joinMulticastGroup() [2/2]

Error UdpSocket::joinMulticastGroup ( const SocketAddress group,
const String iface 
)

Joins a multicast group on a specific interface.

Parameters
groupThe multicast group address.
ifaceThe network interface name (e.g. "eth0").
Returns
Error::Ok on success, or an error on failure.

◆ leaveMulticastGroup()

Error UdpSocket::leaveMulticastGroup ( const SocketAddress group)

Leaves a multicast group.

Parameters
groupThe multicast group address.
Returns
Error::Ok on success, or an error on failure.

◆ open()

Error UdpSocket::open ( OpenMode  mode)
overridevirtual

Opens the socket.

Creates an AF_INET SOCK_DGRAM socket. Use openIpv6() if IPv6 is needed.

Parameters
modeThe open mode (typically ReadWrite).
Returns
Error::Ok on success, or an error on failure.

Implements IODevice.

◆ openIpv6()

Error UdpSocket::openIpv6 ( OpenMode  mode)

Opens the socket for IPv6 operation.

Creates an AF_INET6 SOCK_DGRAM socket. By default, IPV6_V6ONLY is disabled so IPv4-mapped addresses work.

Parameters
modeThe open mode.
Returns
Error::Ok on success, or an error on failure.

◆ pendingDatagramSize()

ssize_t UdpSocket::pendingDatagramSize ( ) const

Returns the size of the next pending datagram.

Returns
The datagram size in bytes, or -1 if no datagram.

◆ read()

int64_t UdpSocket::read ( void data,
int64_t  maxSize 
)
overridevirtual

Reads data from a connected UDP socket.

Requires a prior connectToHost() call.

Parameters
dataBuffer to read into.
maxSizeMaximum bytes to read.
Returns
Bytes read, or -1 on error.

Implements IODevice.

◆ readDatagram()

ssize_t UdpSocket::readDatagram ( void data,
size_t  maxSize,
SocketAddress sender = nullptr 
)

Receives a datagram.

Parameters
dataBuffer to receive into.
maxSizeMaximum bytes to receive.
[out]senderIf not null, receives the sender's address.
Returns
Bytes received, or -1 on error.

◆ setDscp()

Error UdpSocket::setDscp ( uint8_t  dscp)

Sets the DSCP (Differentiated Services) value.

Used for QoS marking on outgoing packets. The value is the 6-bit DSCP field shifted left by 2 to form the full TOS byte (e.g. AF41 = 0x22 << 2 = 0x88, but pass 0x22).

Parameters
dscpThe DSCP value (0-63).
Returns
Error::Ok on success, or an error on failure.

◆ setMulticastInterface()

Error UdpSocket::setMulticastInterface ( const String iface)

Sets the outgoing multicast interface.

Parameters
ifaceThe network interface name (e.g. "eth0").
Returns
Error::Ok on success, or an error on failure.

◆ setMulticastLoopback()

Error UdpSocket::setMulticastLoopback ( bool  enable)

Enables or disables multicast loopback.

When enabled, multicast packets sent on this socket are looped back to local receivers on the same host.

Parameters
enableTrue to enable loopback, false to disable.
Returns
Error::Ok on success, or an error on failure.

◆ setMulticastTTL()

Error UdpSocket::setMulticastTTL ( int  ttl)

Sets the multicast TTL (time to live).

Parameters
ttlThe TTL value (1-255).
Returns
Error::Ok on success, or an error on failure.

◆ setReuseAddress()

Error UdpSocket::setReuseAddress ( bool  enable)

Enables or disables SO_REUSEADDR.

Must be called before bind(). Required for multiple processes to receive from the same multicast group+port.

Parameters
enableTrue to enable, false to disable.
Returns
Error::Ok on success, or an error on failure.

◆ write()

int64_t UdpSocket::write ( const void data,
int64_t  maxSize 
)
overridevirtual

Writes data to a connected UDP socket.

Requires a prior connectToHost() call.

Parameters
dataData to send.
maxSizeBytes to send.
Returns
Bytes sent, or -1 on error.

Implements IODevice.

◆ writeDatagram() [1/2]

ssize_t UdpSocket::writeDatagram ( const Buffer data,
const SocketAddress dest 
)

Sends a Buffer as a datagram.

Parameters
dataThe buffer to send.
destThe destination address and port.
Returns
Bytes sent, or -1 on error.

◆ writeDatagram() [2/2]

ssize_t UdpSocket::writeDatagram ( const void data,
size_t  size,
const SocketAddress dest 
)

Sends a datagram to a specific destination.

Parameters
dataPointer to the data.
sizeNumber of bytes to send.
destThe destination address and port.
Returns
Bytes sent, or -1 on error.

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