Reputation: 5211
Currently, I have working, functioning code to pass messages between two programs I have written. Here's the scheme I'm using:
a_tx_socket -> Send Data on 127.0.0.1, Port A
a_rx_socket -> Receive Data on 127.0.0.1, Port B
b_tx_socket -> Send Data on 127.0.0.1, Port B
b_rx_socket -> Receive Data on 127.0.0.1, Port A
Note that I call bind() on the sockets that receive data (a_rx_socket and b_rx_socket). Each socket is created with a call to the socket() system call.
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? Is this worth exploring for any reason (performance/maintainability/fun/etc)?
Upvotes: 0
Views: 1414
Reputation: 30577
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.
For ip addresses, the socket address is made up of the port and the IP address. See 'man 7 ip' for details.
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.
Upvotes: 2