Non blocking udp socket send receive

client-servernetworkingsockets

I'm writing some embedded Linux software where we have two microprocessors on the same PCB and they communicate with each other using UDP through a switch that is embedded on the PCB. Each application has a hard coded IP address. I want to use non blocking send and receive and I found some example code here
client
and
server

Why does one of them have to be a server? I want to do peer to peer communication between the two microprocessors. Can both of my embedded applications use udpClientNonBlock.c style code or does one have to be a server?

It seems the difference between server and client is that server calls bind(), listens for all incoming IP addresses and doesn't seem to be non-blocking on receive. Neither the server or client know their own IP address and in the sendto message sent by the server, it uses a destination IP address that came from the incoming recvfrom function.

The target code runs on Linux but I want to test it on Windows first. Is it possible to have two applications running on the same PC that talk to each other using UDP ?

In the client code in the example above, a port number is specified as part of the server address and the server listens on that port. In the client code recvfrom function, does the client receive all messages regardless of the port number or only from the port specified as part of the server IP address ?

Best Answer

UDP does not require either end to be strictly a server or client. Each endpoint can react to incoming messages and send outgoing messages.

Each endpoint that wants to receive messages uses bind(2) to associate the socket with its hard-coded (local) address [that is why a server binds, so clients can use the address to connect to the server].

The challenge is deciding when and how long to wait for incoming messages, and when to send outgoing messages. Based upon your description, you are going to want each endpoint to bind(), and either use select(2) or fcntl(2) to configure the sockets as non-blocking. You can either use threading and have a reader thread block on incoming messages, or select(2)/poll for messages.

You may end up with an event loop.