简体   繁体   English

用于IPC的Linux环回UDP套接字

[英]Linux Loopback UDP Sockets For IPC

Currently, I have working, functioning code to pass messages between two programs I have written. 目前,我有工作,功能正常的代码在我编写的两个程序之间传递消息。 Here's the scheme I'm using: 这是我正在使用的方案:

Program A 计划A.

  • a_tx_socket -> Send Data on 127.0.0.1, Port A a_tx_socket - >在端口A的127.0.0.1上发送数据

  • a_rx_socket -> Receive Data on 127.0.0.1, Port B a_rx_socket - >接收端口B上127.0.0.1的数据

Program B 方案B.

  • b_tx_socket -> Send Data on 127.0.0.1, Port B b_tx_socket - >在端口B的127.0.0.1上发送数据

  • b_rx_socket -> Receive Data on 127.0.0.1, Port A b_rx_socket - >接收端口A上127.0.0.1的数据

Note that I call bind() on the sockets that receive data (a_rx_socket and b_rx_socket). 请注意,我在接收数据的套接字(a_rx_socket和b_rx_socket)上调用bind()。 Each socket is created with a call to the socket() system call. 每个套接字都是通过调用socket()系统调用创建的。

Now, for my question... is there a way to get rid of one port? 现在,对于我的问题......有没有办法摆脱一个端口? Namely can I send/receive on the loopback address using only one port? 即只能使用一个端口在环回地址上发送/接收? How would I make sure that Program A/B does not receive data that it sent? 我如何确保程序A / B不接收它发送的数据? Is this worth exploring for any reason (performance/maintainability/fun/etc)? 这是值得探索的任何原因(性能/可维护性/乐趣/等)?

Only one process at a time can bind to a given socket address. 一次只有一个进程可以绑定到给定的套接字地址。 Subsequent attempts to bind will get EADDRINUSE, meaning that the address is already in use. 后续尝试绑定将获得EADDRINUSE,这意味着该地址已被使用。

For ip addresses, the socket address is made up of the port and the IP address. 对于IP地址,套接字地址由端口和IP地址组成。 See ' man 7 ip ' for details. 有关详细信息,请参阅' man 7 ip '。

Therefore, you need two ports, because otherwise only one of your two programs would be able to bind (and therefore receive packets). 因此,您需要两个端口,因为否则只有两个程序中的一个能够绑定(因此接收数据包)。

If your pair of programs is always going to be on the same machine, you might want to use unix domain sockets instead, as they would be more efficient for that use case. 如果您的程序对总是在同一台机器上,那么您可能希望使用unix域套接字,因为它们对于该用例更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM