简体   繁体   中英

Single socket multiple ports or Multiple sockets multiple ports for send and recv

Please excuse me as I am unable to frame the question without depicting my scenario. My scenario is as expalined below,

I have two machines machine1 and machine2 both having its own IP address. Now I want to exchange messages between them, I want to send a message to machine2 from amachine1 in one port say 50 and recv a message from machine2 at port number 51. How can I implement this, I am in confusion whether to create two socket for send and recv in each machine? or just different ports will do the job. I am using C language and Ubuntu linux. Thanks in advance.

                MACHINE1                                  MACHINE2
                    |                                         |
                    |                 sendto                  |
                 port 50 ---------------------------------->  |
                    |                                         |
                    |                recvfrom                 |
                 port51  <--------------------------------    |
                    |                                         |
                    |                                         |

If you just want to send and receive data, a TCP/IP connection will do. You need to choose one of these machines to be the server, for example, one will listen at port 50 (the server) and the client will connect to it.

You can also use UDP and use the same port on two different machines. It is a matter of choice and it depends on what you are going to do on your application.

With TCP:

Machine 1 - Listens on port 50

Machine 2 - Connects to Machine1:50

With this connection, you are able to send and receive data.

With UDP:

Machine 1 - Binds to port 50

Machine 2 - Binds to port 50

The IP of Machine 1 and Machine 2 are different. Now you can send and receive data from the combination IP:port.

You can find examples here (TCP/IP): http://www.thegeekstuff.com/2011/12/c-socket-programming/

and for UDP, here: http://gafferongames.com/networking-for-game-programmers/sending-and-receiving-packets/

Regarding the number of sockets, you need one socket for each side of the connection, or one per machine, on your example. When you open a socket, you are able to send and receive data. We say that a connection is bidirectional.

If you want to use two port, then you will need two sockets in Machine1. On first socket, you send data to Machin2. On second socket, you will listen on port 51, and recv message.

It is also possible to use only one port, In which case, a single socket will do both send/recv on Machine1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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