从特定端口发送 UDP 而不绑定 [英] Send UDP from specific port without bind

查看:12
本文介绍了从特定端口发送 UDP 而不绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是有两个进程:

  1. 进程 A 只知道发送.
  2. 进程 B 只知道接收.

并且进程 C 是编译后的二进制文件,因此无法更改.

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

进程 C 必须从 A 接收并发送到 B.我将进程 B 绑定到端口 X.由于进程 A 每次总是从不同的随机端口发送数据,进程 C 向这些端口应答,因此进程 B 永远不会得到数据.

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.

目前我的解决方案:

  • 绑定进程 B 以监听端口 X(使用重用)
  • 绑定进程 A 从端口 X 发送(使用重用)
  • 始终先从 A 开始,然后再从 B 开始.

此解决方案有效,但不一致.

This solution works, but inconsistently.

所以问题是:是否有可能从特定端口发送到 localhost UDP 数据包而不绑定到它?也许有其他解决方案?

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?

这是当前状态的图表:

推荐答案

从单个父进程启动 A 和 B.父进程创建套接字并将其绑定到端口 X.然后它分叉,子进程继承此套接字.然后其中一个进程执行A,另一个执行B.套接字的FD可以在argv中传递给它们.

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.

SO_REUSEPORT 不能可靠工作的原因是因为每个套接字都有自己的输入队列.当数据报到达端口时,操作系统选择其中一个套接字并将消息放入其队列中.如果它选择了 A 使用的套接字,B 将不会看到该消息.我认为没有办法告诉操作系统其中一个套接字仅用于发送,而不是用于接收.

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.

使用继承的socket解决了这个问题,因为它只是一个socket,所以只有一个队列.无论哪个进程调用 recv() 都会得到所有的消息.

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.

这篇关于从特定端口发送 UDP 而不绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆