Rabi Siddique
450 words
2 minutes
Public and Private IP Addresses

I wanted to serve a file from my Linux machine, so I created a directory named server and added a file called file.txt to it. Using Python3, I then set up an HTTP server on port 8000 to serve this file.

An HTTP server on PORT 8000

I could access the file from my mobile device over the PTCL network:

Using the same network

But when I switched to a different network, the file was no longer accessible:

Using a different network

I am in love with the command python3 -m http.server 8000. A good read of this command over here.

The Basics: Public vs. Private IP Addresses#

In the early days of the internet, connecting a computer to the internet was straightforward. You would connect your device to a modem, which provided a single public IP address. This public IP address uniquely identified your device on the internet. As a result, anyone could access your hosted application using this IP address.

However, with the proliferation of multiple devices within a single household (phones, laptops, smart TVs, gaming consoles, etc.), assigning a unique public IP address to each device became impractical.

Enter the router, a device that connects multiple devices within a local network to the internet through a single public IP address.

How Routers Work#

A router serves two main functions:

  • Connecting to the Internet: The router receives a public IP address from your internet service provider (ISP).
  • Creating a Local Network: The router assigns private IP addresses to all devices within your local network. These private IP addresses typically look like 192.168.1.x and are not accessible from outside the local network.

When you run an application on your laptop with a private IP like 192.168.1.10, it works within your local network. Other devices on the same network can access it. Like I was able access the file.txt from my mobile.

But people outside your network can’t access it because private IPs don’t work on the internet. The time when I tried to access file.txt after switching to a different network.

Why Using Public IP Directly Doesn’t Work#

You might think providing your public IP address to external users would solve the issue. But this will still fail because your router doesn’t know which device within your local network should handle the incoming request. The router needs instructions on how to route incoming traffic to the correct internal device and port.

Port Forwarding: The Solution#

Port forwarding is a technique used to direct traffic from a specific port on your public IP address to a specific device and port within your local network.

Port forwarding is a popular and effective method for directing internet traffic to a specific device within a private network. But it is not the only way to achieve this.

Read More Sources#

Public and Private IP Addresses
https://rabisiddique.com/posts/ip-addresses/
Author
Rabi Siddique
Published at
2024-07-20