One TCP socket for sending and receiving packets

Good afternoon. The task is to write one program that will run on two machines on different networks. This program should establish a TCP connection with the same program on another network and they should exchange packets. This is the first time I have encountered such a task, so some difficulties arose.

In the classic client / server architecture, there is a socket for receiving messages and a socket for sending messages. Since my program, in fact, combines a client and a server, the question is - is it possible to implement both receiving and sending on the same TCP socket?

The logic is as follows - we create a tcp socket (in sockaddr_in we fill in the Ip and port of our local machine), we do bind, then we do listen. Then we make connect (in sockaddr_in, fill in the Ip and port of the second machine with whom we want to connect) and accept. It turns out connect, we send a request to the listen queue on the second machine, and then, through accept, we pull this request out of the queue and get a socket descriptor, through which we are already sending and receiving messages.

Will this logic work, or do you need to do something differently?

Thanks a lot.

Upvotes: 1

Views: 2307

Answers (1)

Tony Delroy
Tony Delroy

Reputation: 106236

As Abhinav says, you should use the command line to specify the behaviour you want the program to have. A good way to do that would be:

$ my_program :28728      # try to listen as a server on port 28728
$ my_program hostname:28728    # try to connect as a client

You can find the command line argument from int main(int argc, const char* argv[]) -> if (argc == 2) then argv[1] will have some text, and you can see if the first character is a ':' to know which mode to run the program in.

For the TCP server mode, create a socket, bind, listen and accept a client connection. For the TCP client mode, create a socket and connect to the server.

Once connected, the TCP connection is a peer-to-peer connection with both sides equally empowered to send and receive data using send() and recv().

Whenever I want to write this kind of code, I turn to the GCC libc examples: https://www.gnu.org/software/libc/manual/html_node/Server-Example.html and https://www.gnu.org/software/libc/manual/html_node/Byte-Stream-Example.html to remind me of all the steps.

Upvotes: 2

Related Questions