Understanding Network Protocols: IP, TCP, and UDP

A comprehensive guide to fundamental network protocols

Internet Protocol (IP)

Think of IP addresses like postal addresses for computers. Just as every house needs an address to receive mail, every device on the internet needs an IP address to send and receive data.

Types of IP Addresses


// IPv4 Address Example
192.168.1.1       // Most common format
255.255.255.0     // Subnet mask
127.0.0.1         // Localhost (your own computer)

// IPv6 Address Example
2001:0db8:85a3:0000:0000:8a2e:0370:7334  // Full format
2001:db8:85a3::8a2e:370:7334              // Shortened format
::1                                        // IPv6 localhost

IP Address Classes


// Class A
// Range: 1.0.0.0 to 126.255.255.255
// Used for: Large networks
// Example: 10.0.0.0/8 (Private network)

// Class B
// Range: 128.0.0.0 to 191.255.255.255
// Used for: Medium-sized networks
// Example: 172.16.0.0/12 (Private network)

// Class C
// Range: 192.0.0.0 to 223.255.255.255
// Used for: Small networks
// Example: 192.168.0.0/16 (Private network)

// Special Addresses
// 127.0.0.1 - Localhost
// 169.254.x.x - Link-local addresses
// 224.0.0.0 to 239.255.255.255 - Multicast

Transmission Control Protocol (TCP)

TCP is like a phone call - it establishes a dedicated connection and ensures all information is received correctly and in order.

Use Cases for TCP


// 1. Web Browsing (HTTP/HTTPS)
fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data));

// 2. File Transfer (FTP)
const ftpClient = new FTP();
ftpClient.connect({
    host: "ftp.example.com",
    user: "username",
    password: "password"
});

// 3. Email (SMTP, IMAP, POP3)
const mailOptions = {
    from: "sender@example.com",
    to: "recipient@example.com",
    subject: "Important Document",
    attachments: [{ path: "document.pdf" }]
};

// 4. Remote Access (SSH)
ssh.connect({
    host: 'server.example.com',
    username: 'admin',
    privateKey: require('fs').readFileSync('/path/to/key')
});

TCP Features


// 1. Connection Establishment (Three-way Handshake)
Client -> Server: SYN
Server -> Client: SYN-ACK
Client -> Server: ACK

// 2. Reliable Delivery
if (packetLost || packetCorrupted) {
    resendPacket();
}

// 3. Order Guarantee
const packets = [
    { sequence: 3, data: "World" },
    { sequence: 1, data: "Hello" },
    { sequence: 2, data: "," }
];

// TCP will reorder to: "Hello, World"

User Datagram Protocol (UDP)

UDP is like sending a postcard - it's faster because it doesn't wait for confirmation, but there's no guarantee of delivery or order.

Use Cases for UDP


// 1. Real-time Gaming
class GameServer {
    constructor(port) {
        this.socket = dgram.createSocket('udp4');
        this.players = new Map();
        
        this.socket.on('message', (msg, rinfo) => {
            this.handlePlayerUpdate(msg, rinfo);
        });
    }
    
    handlePlayerUpdate(data, rinfo) {
        // Process player position updates
        // Don't worry if a few packets are lost
        const update = JSON.parse(data);
        this.players.set(update.playerId, {
            position: update.position,
            timestamp: Date.now()
        });
    }
}

// 2. Live Streaming
class VideoStream {
    constructor() {
        this.socket = dgram.createSocket('udp4');
        this.frameBuffer = [];
        
        setInterval(() => {
            this.sendVideoFrame();
        }, 1000 / 30); // 30 fps
    }
    
    sendVideoFrame() {
        // Send frame without waiting for acknowledgment
        // Missing a frame is better than delay
        const frame = this.frameBuffer.shift();
        if (frame) {
            this.socket.send(frame, PORT, HOST);
        }
    }
}

// 3. VoIP Applications
class VoIPClient {
    constructor() {
        this.socket = dgram.createSocket('udp4');
        this.audioBuffer = [];
        
        // Start audio streaming
        this.startAudioStream();
    }
    
    startAudioStream() {
        // Stream audio packets
        // Small delays better than perfect delivery
        setInterval(() => {
            const audioPacket = this.audioBuffer.shift();
            if (audioPacket) {
                this.socket.send(audioPacket, PORT, HOST);
            }
        }, 20); // 50 packets per second
    }
}

UDP Features


// 1. No Connection Establishment
// Just start sending data
socket.send(data, port, host);

// 2. No Guarantee of Delivery
// Application must handle lost packets if needed
class PacketHandler {
    handlePacket(data) {
        // No automatic retransmission
        // App can implement if needed
        if (this.isImportant(data)) {
            this.requestRetransmission();
        } else {
            // Continue without the packet
            this.processData(data);
        }
    }
}

// 3. No Order Guarantee
const packets = [
    { id: 3, data: "World" },
    { id: 1, data: "Hello" },
    { id: 2, data: "," }
];
// UDP will deliver as received, no reordering

Protocol Comparison


// TCP Use Cases (When reliability matters most)
const TCPApplications = {
    webBrowsing: {
        protocol: "HTTP/HTTPS",
        why: "Need guaranteed delivery of all web content"
    },
    fileTransfer: {
        protocol: "FTP/SFTP",
        why: "Cannot afford to lose any part of a file"
    },
    email: {
        protocol: "SMTP/IMAP/POP3",
        why: "Messages must be delivered completely and in order"
    },
    databases: {
        protocol: "Custom TCP",
        why: "Data integrity is crucial"
    }
};

// UDP Use Cases (When speed matters most)
const UDPApplications = {
    gaming: {
        protocol: "Custom UDP",
        why: "Fast updates more important than perfect delivery"
    },
    streaming: {
        protocol: "RTP",
        why: "Better to skip a frame than delay the stream"
    },
    voip: {
        protocol: "SIP/RTP",
        why: "Real-time audio prioritizes speed over perfection"
    },
    monitoring: {
        protocol: "SNMP",
        why: "Regular updates can afford to miss occasionally"
    }
};