从特定端口发送 UDP 无需绑定

编程入门 行业动态 更新时间:2024-10-27 23:24:02
本文介绍了从特定端口发送 UDP 无需绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

问题在于有两个进程:

  • 进程 A 只知道发送.
  • 进程 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.

    所以问题是:是否有可能从特定端口发送到本地主机 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,然后fork,子进程继承这个套接字.然后其中一个进程执行 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 无需绑定

    本文发布于:2023-06-10 05:43:11,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/608220.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:绑定   端口   UDP

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!