I've been working on TUN device for a while and thought I should look into how packets are handled within the kernel. TUN device allows us to handle packets above layer 3. The corresponding entry point within the kernel is ip_rcv() whih can be found here. ip_local_deliver_finish() is the function whichis the exit of the layer 3 responsible for passing data to the layer 4 stack based on the protocol found in the ip header. You can find the function https://elixir.bootlin.com/linux/v2.6.20/source/net/ipv4/ip_input.c#L199. After ip_local_deliver_finish(), the data is sent to the function handling layer 4 protocol such as tcp_v4_rcv(), udp_rcv(), icmp_rcv(). Might be fun to customize your own network stack and make a kernel of your ownđ.
I used Wireshark to observe how packets are exchanged between client and server. Packets are sent by client form some random port. Packets are received by the server with the specified port by the running program.
Client socket program written in python
import socket
# AF_INET refers to ipv4
# SOCK_STREAM refers to TCP protocol
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 3 way handshake(SYN) as socket.SOCK_STREAM is the selected type
# clientSocket.connect(('127.0.0.1', 12345))
clientSocket.connect(('192.168.50.130', 1234))
dataFromServer = clientSocket.recv(1024)
print(dataFromServer.decode())
Server socket program written in python
import socket
s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
while True:
# 3 way handshake(ACK) as socket.SOCK_STREAM is the selected type
clientSocket, addr = s.accept()
print(addr)
clientSocket.send('Thank you for connecting'.encode())
clientSocket.close()
break
Packets form Wireshark
1 0.000000000 127.0.0.1 127.0.0.1 TCP 74 44070 â 1234 [SYN] Seq=0 Win=65495 Len=0 MSS=65495 SACK_PERM=1 TSval=4210716831 TSecr=0 WS=128
2 0.000113299 127.0.0.1 127.0.0.1 TCP 74 1234 â 44070 [SYN, ACK] Seq=0 Ack=1 Win=65483 Len=0 MSS=65495 SACK_PERM=1 TSval=4210716831 TSecr=4210716831 WS=128
Some stuff I learned about socket programming ă»client socket socket.socket, socket.connect ă»server socket socket.connect, socket.bind, socket.listen, socket.accept Client socket sends SYN with socket.connect and server socket sends ACK with socket.accept. Server socket create client-like(temporary) socket for every incoming client socket.