TCP Handshake (part-1)

30.06.2024

cover

A protocol is a set of standard rules that ensure communication between two or more devices. Therefore, TCP is a protocol, and we can say that it is a standard that facilitates communication between devices.

You may have heard about the 3-way handshake (handshaking) required to establish a TCP connection. It might look something like this:

Let’s break it down in simple terms. As usual, the conversation begins with the Client, and the Server responds. First, the Client sends a SYN flag. You may not immediately understand what’s happening, so let’s see it through code and then analyze it:

import socket


def main():
    sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sck.bind(('localhost', 1712))
    sck.listen(1)

    print("I am listening on port 1712")

    (client_socket, address) = sck.accept()

    while True:
        msg = client_socket.recv(1024)
        if not msg:
            break
        print(f"FROM: {address} \nMESSAGE: {msg}")
        print()
    client_socket.close()


if __name__ == "__main__":
    main()

We’ve written the server side. Now, let’s look at the client side. The server is the listener, and the client is the speaker. Remember the rule: The ear doesn’t hear until the mouth speaks. :)

import socket


def main():
    sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sck.connect(('localhost', 1712))
    print("Sending data...")
    sck.sendall(b"Hello server!")
    sck.close()


if __name__ == "__main__":
    main()

The code I’ve written is a bit sparse on comments, but writing comments was just an excuse. By adding comments, I’m explaining this code to you now.

The code I wrote

Now, when we run the server first, followed by the client through the terminal, the server will keep listening. If the client tries to speak but the server doesn’t listen, the client might be frustrated.


The message I received

To fully track these events, we’ll need Wireshark (you might have heard this term more in network hacking—wow!). It should be available for both Windows and Mac. In the next post, we’ll continue with this topic...