问题
The problem is that there are two processes:
- Process A knows only to send.
- 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:
- Bind process B to listen on port X (using reuse)
- Bind process A to send from port X (using reuse)
- Always start first A and than B.
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:
回答1:
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.
来源:https://stackoverflow.com/questions/17336811/send-udp-from-specific-port-without-bind