Misha
Misha

Reputation: 5380

Send UDP from specific port without bind

The problem is that there are two processes:

  1. Process A knows only to send.
  2. Process B knows only to receive.

And process C is a compiled binary so it cannot be changed.

Process C has to receive from A and send to B. I bind process B to port X. Since process A always sends each time from different random port and process C answers it to these ports, process B never get data.

Currently my solution:

This solution works, but inconsistently.

So the question is: Is there a possibility to send to localhost UDP packet from specific port without bind to it? Maybe some other solution?

Here is a diagram for current state:

enter image description here

Upvotes: 5

Views: 4779

Answers (1)

Barmar
Barmar

Reputation: 780673

Start A and B from a single parent process. The parent process creates the socket and binds it to port X. Then it forks, and the child process inherits this socket. One of the processes then executes A, the other executes B. The FD of the socket can be passed to them in argv.

The reason SO_REUSEPORT doesn't work reliably is because each socket has its own input queue. When a datagram arrives on the port, the OS picks one of the sockets and puts the message on its queue. If it picks the socket used by A, B won't see that message. I don't think there's a way to tell the OS that one of the sockets is only intended for sending, not receiving.

Using the inherited socket solve this problem because it's just a single socket, so there's just one queue. Whichever process calls recv() will get all the messages.

Upvotes: 5

Related Questions