simple-socket library 1.5.0
Loading...
Searching...
No Matches
NET::UDPSocket Class Reference

UDP socket class. More...

#include <simple_socket/UDPSocket.h>

Inheritance diagram for NET::UDPSocket:
Collaboration diagram for NET::UDPSocket:

Public Types

enum  ShutdownDirection { STOP_SEND = SHUT_WR , STOP_RECEIVE = SHUT_RD , STOP_BOTH = SHUT_RDWR }

Public Member Functions

 UDPSocket (AddressFamily family=IPv4)
void sendTo (const void *buffer, size_t len, std::string_view foreignAddress, unsigned short foreignPort)
int receiveFrom (void *buffer, size_t len, std::string &sourceAddress, unsigned short &sourcePort)
int timedReceiveFrom (void *buffer, size_t len, std::string &sourceAddress, unsigned short &sourcePort, int timeout)
void setMulticastTTL (unsigned char multicastTTL)
void setMulticastInterfaceAddr (const std::string &address)
void joinGroup (const std::string &multicastGroup)
void leaveGroup (const std::string &multicastGroup)
void setReuseAddress (bool enable)
 Enable or disable local address reuse.
void connect (std::string_view foreignAddress, unsigned short foreignPort)
 establish a connection with the given foreign address and port
int timedConnect (std::string_view foreignAddress, unsigned short foreignPort, int timeout)
 establish a connection with the given foreign address and port
void bind (unsigned short localPort=0)
void bind (std::string_view localAddress, unsigned short localPort=0)
 bind socket to address / port
std::string getLocalAddress () const
unsigned short getLocalPort () const
std::string getForeignAddress () const
unsigned short getForeignPort () const
AddressFamily addressFamily () const noexcept
 return wether this socket was created for IPv4 or IPv6
int nativeHandle () noexcept
 return the native handle of the open socket
int send (const void *buffer, size_t len)
 send data through a connected socket
int receive (void *buffer, size_t len)
 receive data from a bound socket
int timedReceive (void *buffer, size_t len, int timeout)
 receive data from a bound socket, return after the given timespan
void disconnect ()
 Disconnect and unset any foreign addresses.
void shutdown (ShutdownDirection type)
 shutdown the connection in the specified direction
bool peerDisconnected () const noexcept
 returns whether a currently associated peer disconnected

Protected Member Functions

void listen (int backlog=5)
 listen for incoming connections
int sendAll (const void *buffer, size_t len)
 send data through a connected socket
int receiveAll (void *buffer, size_t len)
 receive exactly the requested amount unless the peer disconnects
int accept () const
 allows stream sockets to accept connections into Handles
int timedAccept (int timeout) const
 allows stream sockets timed accept

Protected Attributes

AddressFamily m_family
int m_socket
bool m_peerDisconnected
bool m_connectionOriented

Detailed Description

UDP socket class.

Examples
UDP_Commands.cpp, and UDP_Multicast.cpp.

Definition at line 9 of file UDPSocket.h.

Member Enumeration Documentation

◆ ShutdownDirection

Enumerator
STOP_SEND 

disable all variants of send() on the socket, receive calls still work

STOP_RECEIVE 

disable all variants of receive() on the socket, send calls still work

STOP_BOTH 

disable all send() and receive() calls on the socket

Definition at line 57 of file SimpleSocket.h.

Constructor & Destructor Documentation

◆ UDPSocket()

UDPSocket::UDPSocket ( AddressFamily family = IPv4)

Construct a UDP socket and enable broadcast capabilities

Exceptions
SocketExceptionthrown if unable to create the socket

Definition at line 32 of file UDPSocket.cpp.

Member Function Documentation

◆ accept()

int SimpleSocket::accept ( ) const
protectedinherited

allows stream sockets to accept connections into Handles

Definition at line 144 of file SimpleSocket.cpp.

◆ addressFamily()

AddressFamily NET::InternetSocket::addressFamily ( ) const
inlinenoexceptinherited

return wether this socket was created for IPv4 or IPv6

Definition at line 117 of file InternetSocket.h.

◆ bind() [1/2]

void InternetSocket::bind ( std::string_view localAddress,
unsigned short localPort = 0 )
inherited

bind socket to address / port

Set the local port to the specified port and the local address to an interface.

bind() attaches the local endpoint of the socket to the specified interface and port. Typically all servers use bind() to attach to the local port specified by the used protocol. You just need to call bind if you want to restrict the connection to a specific local interface, or if you want to listen on a specific port. If you are just a client using connect() to connect to a server, calling bind is most likely unnecessary.

To bind to a port < 1023 you need eighter superuser access, or the SUID bit set on your program.

Parameters
localAddresslocal address
localPortlocal port
Exceptions
SocketExceptionthrown if setting local port fails

Definition at line 140 of file InternetSocket.cpp.

◆ bind() [2/2]

void InternetSocket::bind ( unsigned short localPort = 0)
inherited

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Instead of the richer function with more arguments, this bind() binds to any available interface / address

Examples
TCP_Server.cpp, UDP_Commands.cpp, and UDP_Multicast.cpp.

Definition at line 132 of file InternetSocket.cpp.

◆ connect()

void InternetSocket::connect ( std::string_view foreignAddress,
unsigned short foreignPort )
inherited

establish a connection with the given foreign address and port

If you are using a connection oriented socket (like TCPSocket), you have to call connect() on that socket in order to send data. However, if you are using a non-connection oriented socket (like UDPSocket), calling connect on that socket will allow you to use the send() function like on a connection oriented socket. If not connected, you would have to use sendTo

Parameters
foreignAddressforeign address
foreignPortforeign port
Exceptions
SocketExceptionthrown if unable to establish connection
Examples
TCP_Client.cpp.

Definition at line 74 of file InternetSocket.cpp.

◆ disconnect()

void SimpleSocket::disconnect ( )
inherited

Disconnect and unset any foreign addresses.

This will ungracefully abort the connection by sending an RST frame. disconnect() should not be used under normal circumstances, as it will terminate the connection OOB, preventing the other end of the communication from retrieving data that would still be available in the OS buffer.

For normal termination of a connection use shutdown().

Exceptions
SocketExceptionthrown if unable to disconnect

Definition at line 112 of file SimpleSocket.cpp.

◆ getForeignAddress()

std::string InternetSocket::getForeignAddress ( ) const
inherited

Get the foreign address. Call connect() before using this function.

Returns
foreign address
Exceptions
SocketExceptionthrown if unable to fetch foreign address
Examples
TCP_Server.cpp.

Definition at line 168 of file InternetSocket.cpp.

◆ getForeignPort()

unsigned short InternetSocket::getForeignPort ( ) const
inherited

Get the foreign port. Call connect() before using this function.

Returns
foreign port
Exceptions
SocketExceptionthrown if unable to fetch foreign port
Examples
TCP_Server.cpp.

Definition at line 178 of file InternetSocket.cpp.

◆ getLocalAddress()

std::string InternetSocket::getLocalAddress ( ) const
inherited

Get the local address (after binding the socket).

Returns
local address of socket
Exceptions
SocketExceptionthrown if fetch fails

Definition at line 148 of file InternetSocket.cpp.

◆ getLocalPort()

unsigned short InternetSocket::getLocalPort ( ) const
inherited

Get the local port (after binding the socket).

Returns
local port of socket
Exceptions
SocketExceptionthrown if fetch fails

Definition at line 158 of file InternetSocket.cpp.

◆ joinGroup()

void UDPSocket::joinGroup ( const std::string & multicastGroup)

Join the specified multicast group

The multicast group has to be a valid multicast IP Address (224.0.0.0/4)

Parameters
multicastGroupmulticast group address to join
Exceptions
SocketExceptionthrown if unable to join group
Examples
UDP_Multicast.cpp.

Definition at line 103 of file UDPSocket.cpp.

◆ leaveGroup()

void UDPSocket::leaveGroup ( const std::string & multicastGroup)

Leave the specified multicast group

The multicast group has to be a valid multicast IP Address (224.0.0.0/4)

Parameters
multicastGroupmulticast group address to leave
Exceptions
SocketExceptionthrown if unable to leave group
Examples
UDP_Multicast.cpp.

Definition at line 109 of file UDPSocket.cpp.

◆ listen()

void SimpleSocket::listen ( int backlog = 5)
protectedinherited

listen for incoming connections

listen() can be called on a bound socket. The socket will then go into a passive state and accept incoming connections. To answer to an incoming connection call accept() or timedAccept() on the socket.

The backlog is a buffer for incoming connections. If backlog is set to 0, the number of incoming connections is only limited by the operating system. If backlog is set to a value > 0, only the upper limit of connections is set, the OS can limit the number further.

After starting to listen, use accept to accept incoming connections.

Parameters
backlogupper limit of pending incoming connections
Exceptions
SocketException

Definition at line 137 of file SimpleSocket.cpp.

◆ nativeHandle()

int NET::SimpleSocket::nativeHandle ( )
inlinenoexceptinherited

return the native handle of the open socket

Definition at line 68 of file SimpleSocket.h.

◆ peerDisconnected()

bool SimpleSocket::peerDisconnected ( ) const
noexceptinherited

returns whether a currently associated peer disconnected

For stream sockets this is set when the peer closes or resets the connection. Use this function after a call to receive, returned 0 received bytes.

For connected datagram sockets it may also be set when the network reports that the configured peer is unreachable.

The flag is cleared by a successful connect().

Returns
true if a peer disconnected
Examples
TCP_Client.cpp.

Definition at line 132 of file SimpleSocket.cpp.

◆ receive()

int SimpleSocket::receive ( void * buffer,
size_t len )
inherited

receive data from a bound socket

receive() can only be used on a socket that called bind() or connect() before. If you try to use receive() on a not bound socket, SocketException will be thrown.

If using a stream oriented Socket, receive can return a part of a received messge, e.g. if you send 100 bytes, it's possible you will receive 50 bytes two times in a row. However, the order of the sent data will be preserved.

If you are using a datagram oriented sockets, you will only receive whole datagrams. But beware of using a too small buffer. If the receive buffer is too small for the received datagram, the data you didn't read in the receive call will be discared.

If the remote host has closed the connection (on a connection based socket like TCP or SCTP) receive() will return 0. If you are using a connectionless protocol (like UDP) there is no way to determine wheter the connection has been closed by the remote host or not.

Parameters
bufferthe buffer the received data will be written to
lenlength of the provided buffer, receive will not read more than that
Returns
number of bytes received
Exceptions
SocketExceptionin case an error occured

Definition at line 70 of file SimpleSocket.cpp.

◆ receiveAll()

int SimpleSocket::receiveAll ( void * buffer,
size_t len )
protectedinherited

receive exactly the requested amount unless the peer disconnects

receiveAll() repeatedly calls receive() until len bytes have been received. This is useful for fixed-size data on TCP, where one receive() call is not guaranteed to return all bytes sent by the peer.

If the peer closes or resets the connection before len bytes arrive, the function returns the number of bytes received so far. In that case peerDisconnected() is set by the underlying receive() call.

Parameters
bufferbuffer the received data will be written to
lennumber of bytes to receive
Returns
number of bytes received
Exceptions
SocketExceptionon receive errors other than peer loss

Definition at line 188 of file SimpleSocket.cpp.

◆ receiveFrom()

int UDPSocket::receiveFrom ( void * buffer,
size_t len,
std::string & sourceAddress,
unsigned short & sourcePort )

Read up to len bytes data from this socket. The given buffer is where the data will be placed.

In order to receive data, the socket has to be bound at least to a specific port. This is done by explicitly binding the socket, or sending data through the socket.

Parameters
bufferbuffer to receive data
lenmaximum number of bytes to receive
sourceAddressaddress of datagram source
sourcePortport of data source
Returns
number of bytes received
Exceptions
SocketExceptionthrown if unable to receive datagram
Examples
UDP_Commands.cpp.

Definition at line 49 of file UDPSocket.cpp.

◆ send()

int SimpleSocket::send ( const void * buffer,
size_t len )
inherited

send data through a connected socket

send() can only be used on a socket that called connect() before. If you try to use send() on a not connected socket, SocketException will be thrown.

If you are using a stream oriented socket (like TCPSocket), the operating system is allowed to send only a part of the packet you told it to send, so send() will return the number of bytes actually sent. It is your responsibility to resend the data not sent by send()

If you are using a datagram oriented socket (like UDPSocket or SCTPSocket) the operating system will only send and receive complete datagrams, but send() will fail if you are trying to send too much data. In that case SocketException will be thrown.

Parameters
bufferdata to be send
lenlength of the data to be sent
Returns
number of bytes sent
Exceptions
SocketExceptionif sending went wrong

Definition at line 50 of file SimpleSocket.cpp.

◆ sendAll()

int SimpleSocket::sendAll ( const void * buffer,
size_t len )
protectedinherited

send data through a connected socket

sendAll() can only be used on a socket that called connect() before. If you try to use sendAll() on a unconnected socket, a SocketException will be thrown.

When using a stream oriented socket, the operating system is allowed to send only a bit of the data you requested it to send. Because of this, you would have to check the number of sent bytes when using send(), and resend unsent data manually. sendAll() takes that responsibility from you and resends as long as it needs, to completely send the data given to it.

Parameters
bufferdata to be send
lenlength of the data to be sent
Returns
number of bytes sent
Exceptions
SocketException

Definition at line 175 of file SimpleSocket.cpp.

◆ sendTo()

void UDPSocket::sendTo ( const void * buffer,
size_t len,
std::string_view foreignAddress,
unsigned short foreignPort )

Send the given buffer as a UDP datagram to the specified address / port.

Can be substituted with send() if the socket is first connected to an address and port. If sendTo() is used on a connected socket, the destination parameters will be ignored, and the datagram will be sent to the connected socket.

If the message you are trying to send is too long for one of the underlying protocols a SocketException will be thrown. Like send(), sendTo() blocks until the message was sent.

Parameters
bufferdata to be send
lennumber of bytes to write
foreignAddressaddress to send to
foreignPortport number to send to
Exceptions
SocketExceptionthrown if unable to send datagram
Examples
UDP_Commands.cpp, and UDP_Multicast.cpp.

Definition at line 38 of file UDPSocket.cpp.

◆ setMulticastInterfaceAddr()

void UDPSocket::setMulticastInterfaceAddr ( const std::string & address)

Set the interface address on which to send out multicast packets

Parameters
addressIP address of the target interface
Exceptions
SocketExceptionthrown if unable to set address

Definition at line 93 of file UDPSocket.cpp.

◆ setMulticastTTL()

void UDPSocket::setMulticastTTL ( unsigned char multicastTTL)

Set the multicast TTL

Parameters
multicastTTLmulticast TTL
Exceptions
SocketExceptionthrown if unable to set TTL
Examples
UDP_Multicast.cpp.

Definition at line 86 of file UDPSocket.cpp.

◆ setReuseAddress()

void InternetSocket::setReuseAddress ( bool enable)
inherited

Enable or disable local address reuse.

SO_REUSEADDR allows binding a local address that may still be associated with previous connections, e.g. TCP connections in TIME_WAIT. This option should be set before bind().

Parameters
enabletrue to enable address reuse
Exceptions
SocketExceptionif changing the option fails
Examples
TCP_Server.cpp, and UDP_Multicast.cpp.

Definition at line 67 of file InternetSocket.cpp.

◆ shutdown()

void SimpleSocket::shutdown ( ShutdownDirection type)
inherited

shutdown the connection in the specified direction

This will gracefully end a connection by sending a FIN frame. Use this to end a normal communication cycle. To abort a connection see disconnect().

Depending on the specified ShutdownDirection, calls for that direction will stop working. Use this function if you want to have more control than just destroing the socket. It allows you to cut the connection in one direction, or both.

If you use shutdown() on an unconnected socket, the corresponding calls will simply stop working.

Parameters
typethe ShutdownDirection that be used
Exceptions
SocketExceptionin case an error occured
Examples
TCP_Server.cpp.

Definition at line 126 of file SimpleSocket.cpp.

◆ timedAccept()

int SimpleSocket::timedAccept ( int timeout) const
protectedinherited

allows stream sockets timed accept

Definition at line 158 of file SimpleSocket.cpp.

◆ timedConnect()

int InternetSocket::timedConnect ( std::string_view foreignAddress,
unsigned short foreignPort,
int timeout )
inherited

establish a connection with the given foreign address and port

Provides timeout for TCP socket connection establishment. When a timeout occurs, the OS may still continue the connection attempt in the background. Use disconnect() or destroy the socket to avoid this.

Parameters
foreignAddressforeign address
foreignPortforeign port
timeoutthe timeout in ms after which connect will give up and return
Returns
0 on timeout, 1 when connection is established
Exceptions
SocketExceptionthrown if unable to establish connection

Definition at line 84 of file InternetSocket.cpp.

◆ timedReceive()

int SimpleSocket::timedReceive ( void * buffer,
size_t len,
int timeout )
inherited

receive data from a bound socket, return after the given timespan

timedReceive() can only be used on a socket that called bind() or connect before. If you try to use receive() on a not bound socket, SocketException will be thrown.

If using a stream oriented Socket, receive can return a part of a received messge, e.g. if you send 100 bytes, it's possible you will receive 50 bytes two times in a row. However, the order of the sent data will be preserved.

If you are using a datagram oriented sockets, you will only receive whole datagrams. But beware of using a too small buffer. If the receive buffer is too small for the received datagram, the data you didn't read in the receive call will be discared.

If the remote host has closed the connection (on a connection based socket like TCP or SCTP) receive() will return 0. If you are using a connectionless protocol (like UDP) there is no way to determine wheter the connection has been closed by the remote host or not.

Parameters
bufferthe buffer the received data will be written to
lenlength of the provided buffer, receive will not read more than that
timeoutthe timeout in ms after which receive will give up and return
Returns
number of bytes received, 0 on timeout
Exceptions
SocketExceptionin case an error occured
Examples
TCP_Client.cpp.

Definition at line 89 of file SimpleSocket.cpp.

◆ timedReceiveFrom()

int UDPSocket::timedReceiveFrom ( void * buffer,
size_t len,
std::string & sourceAddress,
unsigned short & sourcePort,
int timeout )

Read up to len bytes data from this socket. The given buffer is where the data will be placed. If no host has sent a datagram before the timeout runs out, the function will return without changing the buffer.

In order to receive data, the socket has to be bound at least to a specific port. This is done by explicitly binding the socket, or sending data through the socket.

Parameters
bufferbuffer to receive data
lenmaximum number of bytes to receive
sourceAddressaddress of datagram source
sourcePortport of data source
timeouttimeout in milliseconds
Returns
number of bytes received, 0 on timeout
Exceptions
SocketExceptionthrown if unable to receive datagram
Examples
UDP_Multicast.cpp.

Definition at line 63 of file UDPSocket.cpp.

Member Data Documentation

◆ m_connectionOriented

bool NET::SimpleSocket::m_connectionOriented
protectedinherited

Definition at line 268 of file SimpleSocket.h.

◆ m_family

AddressFamily NET::InternetSocket::m_family
protectedinherited

Definition at line 127 of file InternetSocket.h.

◆ m_peerDisconnected

bool NET::SimpleSocket::m_peerDisconnected
protectedinherited

Definition at line 267 of file SimpleSocket.h.

◆ m_socket

int NET::SimpleSocket::m_socket
protectedinherited

Definition at line 266 of file SimpleSocket.h.


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