Send UDP from specific port without bind

前提是你 提交于 2020-12-04 03:40:36

问题


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:

  • 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:

enter image description here


回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!