I'm in the middle of experimenting with Linux UDP sockets. I have a server and client that are talking to one another in the following way.
Server: Sends broadcast announcement on port X to all IPs on it's subnet.
Client: Responds to the announcement by sending a unicast message back to the server. This message gets sent back directly to port X.
On the server, I have one thread that periodically sends the announcement. I now want to add more code to receive the response from the client as well as send unicast messages to a particular client. I have my proposed scheme for the server outlined below.
Thread 1
- Broadcast on socket_a, which is set up using setsockopt() to set SO_BROADCAST. Sends broadcast announcements on port X.
Thread 2
- Reads in data from port X, using socket_b. Due to limitations with the code's current structure, this thread does not have access to socket_a. Note that the port is shared with socket_a. bind() is called to read in data on this socket.
Thread 3
- Sends unicast data to particular clients using socket_b on port X. Note that both the socket and port are shared with thread 2, and the port is common across all three threads and the two sockets.
In no particular order, here are my questions (bear with me, I'm fairly new to unix socket programming):
Do I need to do any locking between the two sockets or is that handled in the OS? That is, can I send data concurrently to both sockets and not get some weird collisions since both use the same port?
Do I need to worry about Thread 2 receiving data that is sent out by either of the "sender" threads? How do I prevent this?
Are there any options that I need to enable to make this work? Does it matter if the broadcast socket (socket_a) gets set up prior to the unicast one (socket_b)?
Should I create a dedicated "receive" socket on port X? That is, would it make sense to have a socket that is solely used to receive data? This is the only socket that would have bind() called on it.
Are there any other issues I should be worried about given that all three threads are using the same port? Unfortunately, this is a constraint that I am working with. If the above scheme is impossible, I may have to revisit my one port design.
Thank you in advance for your help.