Networking basics, Understanding Sockets and TCP/IP

TCP/IP is the foundation of internet communication, and sockets provide a way for programs to send and receive data over the network. This tutorial introduces how the TCP/IP model works and how sockets are used in network programming.

Step 1: What is TCP/IP?

TCP/IP is a suite of protocols that defines how data is transmitted across networks. It consists of layers:

  • Application Layer: HTTP, FTP, DNS
  • Transport Layer: TCP (reliable), UDP (unreliable)
  • Internet Layer: IP (addresses and routes packets)
  • Network Access Layer: Ethernet, Wi-Fi, etc.

Step 2: What is a Socket?

A socket is an endpoint for sending or receiving data between two machines. It’s defined by:

  • IP Address: Identifies the host
  • Port Number: Identifies the application

Example of a socket: 192.168.1.10:8080

Step 3: TCP vs UDP

  • TCP: Connection-oriented, reliable, ensures ordered delivery (used in web browsing, emails).
  • UDP: Connectionless, fast, less overhead (used in streaming, gaming).

Step 4: Creating a TCP Socket (Pseudocode)

int sock = socket(AF_INET, SOCK_STREAM, 0);
    connect(sock, server_address);
    send(sock, "Hello", 5, 0);
    recv(sock, buffer, sizeof(buffer), 0);

Step 5: Server-Side Sockets

A basic TCP server:

  1. Create socket
  2. Bind to IP and port
  3. Listen for connections
  4. Accept and handle connections

Step 6: Ports and Protocols

  • Port 80: HTTP
  • Port 443: HTTPS
  • Port 22: SSH
  • Port 53: DNS

Step 7: Tools to Inspect TCP/IP

  • netstat: View active connections
  • ss: Socket statistics
  • telnet or nc: Test open ports

Next Steps

Try writing a simple chat application using sockets. Understanding TCP/IP and sockets is key to systems programming, web development, and cybersecurity.