Sobes.tech
Junior — Middle

Can you explain what the TCP protocol is and how it works for establishing connections and data transfer?

sobes.tech AI

Answer from AI

TCP (Transmission Control Protocol) is a transport layer protocol that provides reliable, connection-oriented data transfer between two nodes in a network.

Main features of TCP:

  • Connection establishment (3-way handshake):

    1. The client sends a segment with the SYN flag.
    2. The server responds with a segment with SYN and ACK.
    3. The client confirms receipt with an ACK.
  • Reliability: TCP guarantees delivery of data without loss and in the correct order, using sequence numbers and acknowledgments (ACK).

  • Flow control: prevents receiver overflow.

  • Congestion control: adapts the transmission rate depending on network conditions.

An example of simplified connection establishment in C++ using sockets:

int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(80);
inet_pton(AF_INET, "93.184.216.34", &server_addr.sin_addr); // example.com
connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
// Now the connection is established, and data can be sent and received

Thus, TCP provides a reliable communication channel between applications.