Network Component  
MDK Middleware for IPv4 and IPv6 Networking
 
Loading...
Searching...
No Matches
User API

UDP Socket functions. More...

Typedefs

typedef uint32_t(* netUDP_cb_t) (int32_t socket, const NET_ADDR *addr, const uint8_t *buf, uint32_t len)
 UDP Event callback function.
 

Functions

int32_t netUDP_GetSocket (netUDP_cb_t cb_func)
 Allocate a free UDP socket. [thread-safe].
 
netStatus netUDP_ReleaseSocket (int32_t socket)
 Release UDP socket and free resources. [thread-safe].
 
netStatus netUDP_Open (int32_t socket, uint16_t port)
 Open UDP socket for communication. [thread-safe].
 
netStatus netUDP_Close (int32_t socket)
 Stop UDP communication and close socket. [thread-safe].
 
uint8_t * netUDP_GetBuffer (uint32_t size)
 Allocate memory for UDP send buffer. [thread-safe].
 
netStatus netUDP_Send (int32_t socket, const NET_ADDR *addr, uint8_t *buf, uint32_t len)
 Send data to a remote node. [thread-safe].
 
netStatus netUDP_SetOption (int32_t socket, netUDP_Option option, uint32_t val)
 Set UDP socket IP option. [thread-safe].
 
uint16_t netUDP_GetLocalPort (int32_t socket)
 Retrieve local port number of UDP socket. [thread-safe].
 

Description

UDP Socket functions.

UDP is a byte stream service. It does not know anything about the format of the data being sent. It simply takes the data, encapsulates it into a UDP packet, and sends it to the remote peer.

The UDP protocol does not wait for any acknowledgment and is unable to detect any lost packets. If this is required, it must be done by the application layer. However, it is better to use a TCP Socket for reliable communication.

Sending Data via UDP in Unicast Mode

The function netUDP_Open opens a socket for communication. You need to specify the socket number and the local port to be used. As a first step, you need to establish the communication between two nodes, otherwise netUDP_Send will fail with netError. To avoid this, call a netARP_CacheIP in a first step.

If netUDP_Open is called with a local port number of 0, the Network Core determines which port to use. Later, this information can be retrieved using the function netUDP_GetLocalPort. To set certain UDP options (for IPv4 or IPv6) for the opened socket, use netUDP_SetOption.

To send data via UDP, you first need to request a buffer to be allocated using netUDP_GetBuffer. Then, fill the buffer with the data to be sent and send it using netUDP_Send. The buffer will be released by the Network Component automatically. If the buffer is not valid (not allocated with the netUDP_GetBuffer function), the buffer is ignored.

The Network Component does not send 0-length packets. So it is possible to release a buffer that has been allocated, by simply calling netUDP_Send with parameter len = 0.

The user code template file UDP_Socket.c contains an exemplary send function, called send_data. This shows how to use netUDP_GetBuffer (for memory allocation) and netUDP_Send for data transmission. To add the template to your project, simply right-click on the Source group, select Add New Item to Group, then click on User Code Template and scroll in the template files list until you find the UDP Socket template. Adapt the send_data function to your application's needs.

UDP communication will be stopped using netUDP_Close. The UDP socket will be closed. Subsequently, call netUDP_ReleaseSocket as well, as this function finally frees the memory used by the UDP socket.

Code Example

#include "rl_net.h"
int32_t udp_sock; // UDP socket handle
// Notify the user application about UDP socket events.
uint32_t udp_cb_func (int32_t socket, const NET_ADDR *addr, const uint8_t *buf, uint32_t len) {
// Data received
if ((buf[0] == 0x01) && (len == 2)) {
// Switch LEDs on and off
LED_out (buf[1]);
}
return (0);
}
// Send UDP data to destination client.
void send_udp_data (void) {
if (udp_sock >= 0) {
// IPv4 address: 192.168.0.1
NET_ADDR addr = { NET_ADDR_IP4, 2000, 192, 168, 0, 1 };
// IPv6 address: [fe80::1c30:6cff:fea2:455e]
// NET_ADDR addr = { NET_ADDR_IP6, 2000,
// 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// 0x1c, 0x30, 0x6c, 0xff, 0xfe, 0xa2, 0x45, 0x5e };
uint8_t *sendbuf;
sendbuf = netUDP_GetBuffer (2);
sendbuf[0] = 0x01;
sendbuf[1] = 0xAA;
netUDP_Send (udp_sock, &addr, sendbuf, 2);
}
}
// Allocate and initialize the socket.
int main (void) {
// Initialize UDP socket and open port 2000
udp_sock = netUDP_GetSocket (udp_cb_func);
if (udp_sock >= 0) {
netUDP_Open (udp_sock, 2000);
}
}

Sending Data via UDP in Multicast Mode

To send and receive data to/from multiple hosts, you need to join a specific group of hosts with netIGMP_Join function. Then you can use the same functions as described in Sending Data via UDP in Unicast Mode. When you want to stop sending and receiving the data from that group address, you have to leave a specific group with netIGMP_Leave function.

Typedef Documentation

◆ netUDP_cb_t

uint32_t(* netUDP_cb_t)(int32_t socket, const NET_ADDR *addr, const uint8_t *buf, uint32_t len)

UDP Event callback function.

Parameters
[in]socketUDP socket handle.
[in]addrPointer to the structure containing the remote IP address and port number.
[in]bufPointer to buffer containing the received data.
[in]lenNumber of bytes in the received packet.
Returns
Currently not used. Reserved for future use.

Is the type definition for the UDP callback function. The Network Core calls the callback function whenever a UDP data packet is received. Users must provide the function.

The argument socket is the UDP socket handle of the local machine.

The argument addr is a pointer to the buffer containing the IP address and port of the remote machine, and the IP version IPv4 or IPv6.

The argument buf points to a buffer containing the received data.

The argument len specifies the number of received data bytes. The maximum size of a received data is:

IP Version Maximum data size Fragmentation supported
IPv4 2000 bytes Yes
IPv6 2000 bytes Yes

If the IP fragmentation is not supported or is disabled in the configuration, received fragmented IP packets are dumped by the stack automatically. Therefore, it is not possible to receive mega UDP frames up to 64K.

Parameter for:

Note
  • The IPv4 fragmentation must be enabled in the Network interface configuration.

Code Example

uint32_t udp_cb_func (int32_t socket, const NET_ADDR *addr, const uint8_t *buf, uint32_t len) {
// Data received
if ((buf[0] == 0x01) && (len == 2)) {
// Switch LEDs on and off
// LED_SetOut (buf[1]);
}
return (0);
}

Code Example IPv4 only

uint32_t udp_cb_func (int32_t socket, const NET_ADDR *addr, const uint8_t *buf, uint32_t len) {
if (addr->addr_type == NET_ADDR_IP6) {
// Dump IPv6 data
return (0);
}
if ((buf[0] == 0x01) && (len == 2)) {
// Switch LEDs on and off
// LED_SetOut (buf[1]);
}
return (0);
}

Function Documentation

◆ netUDP_Close()

netStatus netUDP_Close ( int32_t  socket)

Stop UDP communication and close socket. [thread-safe].

Parameters
[in]socketsocket handle obtained with netUDP_GetSocket.
Returns
status code that indicates the execution status of the function.

The netUDP_Close function closes the UDP socket identified in the function argument. After calling the netUDP_Close function, the UDP socket cannot send or receive any data packet. After closing the UDP socket, you can reopen it using the netUDP_Open function.

The UDP socket still reserves memory after calling the netUDP_Close function. Hence, if you do not need the socket, you must release the memory using the netUDP_ReleaseSocket function after calling netUDP_Close.

Possible netStatus return values:

  • netOK: Socket closed successfully.
  • netInvalidParameter: Invalid socket requested.

Code Example (see netUDP_ReleaseSocket)

◆ netUDP_GetBuffer()

uint8_t * netUDP_GetBuffer ( uint32_t  size)

Allocate memory for UDP send buffer. [thread-safe].

Parameters
[in]sizenumber of bytes to allocate.
Returns
pointer to the allocated memory.
  • NULL = out of memory.

The function netUDP_GetBuffer allocates memory for the UDP send buffer into which your application can write the outgoing data packet.

The argument size specifies the number of data bytes that the application wants to send. When the UDP frame has been sent, the Network Core automatically de-allocates the memory used by the send buffer.

Note
  • Your application must call the netUDP_GetBuffer function each time it wants to send a UDP data packet.
  • The total size of the allocated memory must not exceed the UDP Maximum Packet Size (1452 bytes).
  • Writing more data than the allocated size of the data buffer overwrites the Memory Manager Block links and causes the Network Core to crash.

Code Example (see netUDP_Send)

◆ netUDP_GetLocalPort()

uint16_t netUDP_GetLocalPort ( int32_t  socket)

Retrieve local port number of UDP socket. [thread-safe].

Parameters
[in]socketsocket handle obtained with netUDP_GetSocket.
Returns
local port number.
  • 0 = socket invalid or in invalid state.

The function netUDP_GetLocalPort returns the port number for the specified socket. This is useful if you have not specified a port in the netUDP_Open function as the system sets the port automatically then.

Code Example

int32_t udp_sock;
udp_sock = netUDP_GetSocket (udp_cb_func);
if (udp_sock >= 0) {
netUDP_Open (udp_sock, 0);
printf ("Local port is %d\n", netUDP_GetLocalPort (udp_sock));
}

◆ netUDP_GetSocket()

int32_t netUDP_GetSocket ( netUDP_cb_t  cb_func)

Allocate a free UDP socket. [thread-safe].

Parameters
[in]cb_funcevent listening callback function.
Returns
socket handle number or execution status:
  • value >= 0: socket handle number.
  • value < 0: error occurred, -value is execution status as defined with netStatus.

The function netUDP_GetSocket allocates a free UDP socket. It initializes all state variables of the UDP socket to the default state. By default, a checksum will be calculated for every UDP packet. To turn this off, use the netUDP_SetOption function.

The argument cb_func is the event callback function of the UDP socket. Users must provide this function. Refer to netUDP_cb_t.

Possible netStatus return values:

  • netInvalidParameter: Callback function not valid.
  • netError: No free sockets available.
Note
  • You must call the netUDP_GetSocket function before any other function calls to the UDP socket.
  • You must define the listener function to use with the UDP socket.
  • UDP socket is IP version agnostic (supports both IPv4 and IPv6).

Code Example

int32_t udp_sock;
uint32_t udp_cb_func (int32_t socket, const NET_ADDR *addr, const uint8_t *buf, uint32_t len) {
..
return (0);
}
// Initialize UDP socket and open port 2000
udp_sock = netUDP_GetSocket (udp_cb_func);
if (udp_sock >= 0) {
netUDP_Open (udp_sock, 2000);
}

◆ netUDP_Open()

netStatus netUDP_Open ( int32_t  socket,
uint16_t  port 
)

Open UDP socket for communication. [thread-safe].

Parameters
[in]socketsocket handle obtained with netUDP_GetSocket.
[in]portlocal port number.
  • 0 = system assigned local port.
Returns
status code that indicates the execution status of the function.

The netUDP_Open function opens the UDP socket identified by the argument socket for communication.

The argument port specifies the local port for sending and receiving data packets. If port is set to 0, then the Network Core allocates the first free UDP port automatically. If you need the port number later, use netUDP_GetLocalPort to retrieve this information.

Possible netStatus return values:

  • netOK: Socket opened successfully.
  • netInvalidParameter: Invalid socket requested or port not available.
  • netWrongState: Socket already opened.

Code Example (see netUDP_GetSocket)

◆ netUDP_ReleaseSocket()

netStatus netUDP_ReleaseSocket ( int32_t  socket)

Release UDP socket and free resources. [thread-safe].

Parameters
[in]socketsocket handle obtained with netUDP_GetSocket.
Returns
status code that indicates the execution status of the function.

The function netUDP_ReleaseSocket releases the socket and de-allocates its memory.

Possible netStatus return values:

  • netOK: Socket released successfully.
  • netInvalidParameter: Invalid socket requested.
  • netWrongState: Socket not closed.
Note
  • Once the socket is released, the Network Core can allocate the socket to another process.
  • You must call the netUDP_ReleaseSocket function when you do not need the UDP socket any longer.

Code Example

// This UDP connection is no longer needed
netUDP_Close (udp_sock);

◆ netUDP_Send()

netStatus netUDP_Send ( int32_t  socket,
const NET_ADDR addr,
uint8_t *  buf,
uint32_t  len 
)

Send data to a remote node. [thread-safe].

Parameters
[in]socketsocket handle obtained with netUDP_GetSocket.
[in]addrstructure containing remote IP address and port.
[in]bufbuffer containing the data.
[in]lenlength of data in bytes.
Returns
status code that indicates the execution status of the function.

The function netUDP_Send sends the data packet to a remote machine.

The argument socket specifies the socket handle to use for communication on the local machine.

The argument addr points to a buffer containing the IP address and port of the remote machine.

The argument buf points to the constructed UDP data packet.

The argument len specifies the number of bytes in the data packet. The maximum size of a transmitted data is:

IP Version Maximum data size Fragmentation supported
IPv4 2000 bytes Yes
IPv6 2000 bytes Yes

Over-sized transmit packets are truncated to the maximum size before being sent. Therefore, it is not possible to send mega UDP frames up to 64K.

Possible netStatus return values:

  • netOK: Send data successful.
  • netInvalidParameter: Invalid or not supported parameter provided.
  • netWrongState: Socket not open.
  • netError: Send data failed.
Note
  • You must allocate the memory using netUDP_GetBuffer before calling netUDP_Send.
  • The buffer will be released, no matter if netUDP_Send is successful or not.
  • netUDP_Send does not send 0-length packets. It is possible to release a buffer that has been allocated, by simply calling netUDP_Send with parameter len = 0.
  • The socket must already be open for communication before you can send data.
  • The same UDP socket, using the same local port, can communicate with several remote machines using UDP ports. The user application must handle proper multiplexing of outgoing packets and demultiplexing of received packets.

Code Example IPv4

// IPv4 address: 192.168.0.1
NET_ADDR4 addr = { NET_ADDR_IP4, 2000, 192, 168, 0, 1 };
uint8_t *sendbuf;
sendbuf = netUDP_GetBuffer (2);
sendbuf[0] = 0x01;
sendbuf[1] = 0xAA;
netUDP_Send (udp_sock, (NET_ADDR *)&addr, sendbuf, 2);

Code Example IPv6

// IPv6 address: [fe80::1c30:6cff:fea2:455e]
NET_ADDR addr = { NET_ADDR_IP6, 2000,
0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x1c, 0x30, 0x6c, 0xff, 0xfe, 0xa2, 0x45, 0x5e };
uint8_t *sendbuf;
sendbuf = netUDP_GetBuffer (2);
sendbuf[0] = 0x01;
sendbuf[1] = 0xAA;
netUDP_Send (udp_sock, &addr, sendbuf, 2);

◆ netUDP_SetOption()

netStatus netUDP_SetOption ( int32_t  socket,
netUDP_Option  option,
uint32_t  val 
)

Set UDP socket IP option. [thread-safe].

Parameters
[in]socketsocket handle obtained with netUDP_GetSocket.
[in]optionoption name as defined with netUDP_Option.
[in]valoption value.
Returns
status code that indicates the execution status of the function.

The function netUDP_SetOption sets different options for an UDP socket identified by the argument socket.

The argument option specifies the UDP option that is to be set (see below).

The argument val carries the value of the UDP option that is to be set.

Option Description Value
netUDP_OptionTOS IPv4 Type of Service val=TOS
netUDP_OptionTTL IPv4 Multi-cast Time to Live val=TTL
netUDP_OptionTrafficClass IPv6 Traffic Class val=TrafficClass
netUDP_OptionHopLimit IPv6 Multi-cast Hop Limit val=HopLimit
netUDP_OptionInterface Network interface to bind val=if_id (class and number)
netUDP_OptionChecksum UDP Checksum Options val=Options

The option netUDP_OptionInterface specifies the network interface to be used for sending the broadcast message in the local network. By default the broadcast message is routed to the first LAN interface from the list where IPv4 is enabled. You can use this option to change the default interface for sending broadcast messages. Only used in IPv4.

For the option netUDP_OptionChecksum the argument val is a combination of:

Possible netStatus return values:

  • netOK: Option successfully set.
  • netInvalidParameter: Invalid parameter provided.
  • netWrongState: Requested socket not allocated.

Code Example

int32_t udp_sock;
udp_sock = netUDP_GetSocket (udp_cb_func);
if (udp_sock >= 0) {
// Open UDP port 1000 for communication.
netUDP_Open (udp_sock, 1000);
// Let UDP Multicast datagrams cross a router.
}