A user off this forum Cedric Velandres asked me how to do UDP broadcasting in FreeRTOS+TCP. As more users might be interested, I will post the answer here.
You create the socket in the normal way:
Socket_t xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );
You bind it in the normal way:
struct freertos_sockaddr xAddress; /* Auto bind the port. */ xAddress.sin_port = 0u; xReturn = FreeRTOS_bind( xSocket, &xAddress, sizeof( xAddress ) );
Port 0 means: take a random UDP port that is available, non-zero means: take a specific port number.
You can use
recvfrom() in the normal way, see for instance this post.
The UDP socket is created once, and you can use it to talk with any unit on the LAN or Internet, using mentioned port.
Note that for non-broadcast messages, the first message to a peer may get lost: the packet is changed into an ARP-request. If that peer is the first one to send you a message, it’s address is stored in the ARP table, and no ARP look-up will be needed.
In a big OS, you’d have to give broadcast permission (
SO_BROADCAST ) to a socket. Within FreeRTOS+TCP that is not necessary. You can do both broadcast and unicast with the same socket.
recvfrom() gives you the address of the sender. You can use that address to send (unicast) a reply to that unit.