Networking

IPv4

Internet Protocol version 4 - The fourth version of the Internet Protocol that uses 32-bit addresses to identify devices on a network, supporting approximately 4.3 billion unique addresses.

What is IPv4?

IPv4 (Internet Protocol version 4) is the fourth version of the Internet Protocol and the most widely deployed protocol for routing internet traffic. It uses 32-bit addresses written in dotted-decimal notation (e.g., 192.168.1.1) and provides the foundation for modern internet communication.

IPv4 Address Structure

Address Format

192.168.1.100

Binary representation:
11000000.10101000.00000001.01100100

32 bits total = 4 bytes (octets)
Each octet: 0-255
Total addresses: 2^32 = 4,294,967,296

Address Classes

// Class A: 1.0.0.0 to 126.255.255.255
// Network bits: 8, Host bits: 24
// Used for: Large networks (16.7M hosts)

// Class B: 128.0.0.0 to 191.255.255.255
// Network bits: 16, Host bits: 16
// Used for: Medium networks (65,536 hosts)

// Class C: 192.0.0.0 to 223.255.255.255
// Network bits: 24, Host bits: 8
// Used for: Small networks (254 hosts)

// Class D: 224.0.0.0 to 239.255.255.255
// Used for: Multicast

// Class E: 240.0.0.0 to 255.255.255.255
// Reserved for experimental use

Private IPv4 Ranges

Reserved Address Spaces

interface PrivateRanges {
  classA: '10.0.0.0/8';           // 10.0.0.0 - 10.255.255.255
  classB: '172.16.0.0/12';        // 172.16.0.0 - 172.31.255.255
  classC: '192.168.0.0/16';       // 192.168.0.0 - 192.168.255.255
  loopback: '127.0.0.0/8';        // 127.0.0.1 (localhost)
  linkLocal: '169.254.0.0/16';    // Auto-configuration
}

// Example: Check if IP is private
function isPrivateIPv4(ip: string): boolean {
  const parts = ip.split('.').map(Number);
  const firstOctet = parts[0];
  const secondOctet = parts[1];

  // Class A private
  if (firstOctet === 10) return true;

  // Class B private
  if (firstOctet === 172 && secondOctet >= 16 && secondOctet <= 31) return true;

  // Class C private
  if (firstOctet === 192 && secondOctet === 168) return true;

  // Loopback
  if (firstOctet === 127) return true;

  return false;
}

IPv4 with Proxy Servers

Specifying IPv4 in Requests

// Using CorsProxy with IPv4
const response = await fetch(
  'https://corsproxy.io/?url=https://api.example.com/data',
  {
    headers: {
      'x-cors-api-key': process.env.CORS_API_KEY,
      'x-cors-proxy-type': 'datacenter',
      // Proxy will use IPv4 by default
    }
  }
);

// Getting your current IPv4 address
const ipResponse = await fetch('https://api.ipify.org?format=json');
const { ip } = await ipResponse.json();
console.log(`Your IPv4: ${ip}`);

IPv4 Proxy Configuration

class IPv4ProxyManager {
  private proxyList: string[];

  constructor(proxies: string[]) {
    this.proxyList = proxies;
  }

  // Rotate through IPv4 proxies
  getNextProxy(): string {
    const proxy = this.proxyList.shift();
    if (proxy) {
      this.proxyList.push(proxy);
      return proxy;
    }
    throw new Error('No proxies available');
  }

  // Validate IPv4 format
  isValidIPv4(ip: string): boolean {
    const parts = ip.split('.');
    if (parts.length !== 4) return false;

    return parts.every(part => {
      const num = parseInt(part, 10);
      return num >= 0 && num <= 255 && part === num.toString();
    });
  }
}

// Usage
const manager = new IPv4ProxyManager([
  '203.0.113.1:8080',
  '203.0.113.2:8080',
  '203.0.113.3:8080'
]);

const proxy = manager.getNextProxy();

CIDR Notation

Subnet Masks

// CIDR (Classless Inter-Domain Routing)
// Format: IP/prefix-length

interface CIDRBlock {
  notation: '192.168.1.0/24';
  netmask: '255.255.255.0';
  network: '192.168.1.0';
  broadcast: '192.168.1.255';
  usableIPs: 254;                    // .1 to .254
  totalIPs: 256;
}

// Calculate network range
function calculateCIDR(cidr: string) {
  const [ip, prefixStr] = cidr.split('/');
  const prefix = parseInt(prefixStr, 10);

  const totalIPs = Math.pow(2, 32 - prefix);
  const usableIPs = totalIPs - 2; // Subtract network and broadcast

  return {
    ip,
    prefix,
    totalIPs,
    usableIPs,
    subnetMask: calculateSubnetMask(prefix)
  };
}

function calculateSubnetMask(prefix: number): string {
  const mask = ~((1 << (32 - prefix)) - 1);
  return [
    (mask >>> 24) & 255,
    (mask >>> 16) & 255,
    (mask >>> 8) & 255,
    mask & 255
  ].join('.');
}

// Examples
console.log(calculateCIDR('10.0.0.0/8'));    // 16,777,216 IPs
console.log(calculateCIDR('172.16.0.0/12')); // 1,048,576 IPs
console.log(calculateCIDR('192.168.1.0/24')); // 256 IPs

IPv4 Exhaustion

The Address Shortage

Total IPv4 addresses: 4,294,967,296
Reserved/Private: ~600 million
Publicly routable: ~3.7 billion

World population: 8+ billion
Internet users: 5+ billion
Connected devices: 50+ billion

Solution: IPv6 (340 undecillion addresses)

NAT (Network Address Translation)

// NAT allows multiple devices to share one public IPv4
/*
Public IPv4: 203.0.113.50

Private Network:
├─ 192.168.1.10 (Device 1)
├─ 192.168.1.11 (Device 2)
└─ 192.168.1.12 (Device 3)

All devices share 203.0.113.50 for outbound connections
*/

// Detecting NAT
async function detectNAT() {
  // Get public IP
  const publicResponse = await fetch('https://api.ipify.org?format=json');
  const { ip: publicIP } = await publicResponse.json();

  // Get local IP (browser example)
  const pc = new RTCPeerConnection({ iceServers: [] });
  pc.createDataChannel('');
  const offer = await pc.createOffer();
  await pc.setLocalDescription(offer);

  const localIP = offer.sdp.split('\n')
    .find(line => line.includes('candidate'))
    ?.match(/\d+\.\d+\.\d+\.\d+/)?.[0];

  return {
    publicIP,
    localIP,
    behindNAT: publicIP !== localIP
  };
}

IPv4 Geolocation

IP-Based Location Lookup

interface IPv4Location {
  ip: string;
  country: string;
  countryCode: string;
  region: string;
  city: string;
  latitude: number;
  longitude: number;
  isp: string;
  timezone: string;
}

async function geolocateIPv4(ip: string): Promise<IPv4Location> {
  const response = await fetch(`https://ipapi.co/${ip}/json/`);
  return response.json();
}

// Usage with proxy
const location = await geolocateIPv4('8.8.8.8');
console.log(`IP ${location.ip} is in ${location.city}, ${location.country}`);

IPv4 vs IPv6

Key Differences

interface ProtocolComparison {
  ipv4: {
    addressSize: 32;              // bits
    format: '192.0.2.1';
    totalAddresses: '4.3 billion';
    header: '20-60 bytes';
    security: 'Optional (IPsec)';
    configuration: 'DHCP or manual';
  };
  ipv6: {
    addressSize: 128;             // bits
    format: '2001:0db8::1';
    totalAddresses: '340 undecillion';
    header: '40 bytes (fixed)';
    security: 'Built-in (IPsec)';
    configuration: 'Auto (SLAAC)';
  };
}

Best Practices

For Developers

  1. Always validate IPv4 format before use
  2. Handle both IPv4 and IPv6 in applications
  3. Use CIDR notation for network ranges
  4. Implement proper error handling for IP operations

For Network Configuration

  1. Use private ranges for internal networks
  2. Implement NAT for address conservation
  3. Plan for IPv6 transition
  4. Monitor IP address allocation

Learn More

Create a free Account to fix CORS Errors in Production

Say goodbye to CORS errors and get back to building great web applications. It's free!

CORSPROXY Dashboard

Related Terms

More in Networking

Back to Glossary