How to access localhost on your dev machine with your phone

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the networking category.

Last Updated: 2024-11-23

I wanted to carry out a simple challenge on my home network: run a server on my laptop (localhost:3000) and then visit this from my mobile phone (on the same WIFI network and then from an external network)

Preview:

Part 1 (internal network): With my laptop firewall opened for the Ruby server port, this was as easy as finding my laptop's exact IP address in the network and typing it into my phone's browser (i.e., at the time: 192.168.2.107:3000). The main gotcha was making sure I was on the same WIFI network (and not letting my phone switch to the mobile data network!)

Part 2 (external network): This required mapping an external port in my router to the static IP address server/port in my network.

Basics Refresher

How to get ip/mac addresses

How to get your private IP address?

The private IP address is what your machine is known as within your network (but not over the wider internet)

$ ifconfig

Then browse for likely candidates. Probably under en0

=> en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether dc:a9:04:72:0b:8a
inet 192.168.2.107

How to get your public IP address?

If you are behind a router, then your computer will not know about its public IP address since the router does a network address translation (NAT). Instead you should ask some website what your public IP address is using curl and extract the information you need from it. Here is one such service:

$ curl ipecho.net/plain

What ports do I have open?

$ nmap localhost

Starting Nmap 7.80 ( https://nmap.org ) at 2019-08-29 04:45 CEST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00055s latency).
Other addresses for localhost (not scanned): ::1
Not shown: 970 closed ports, 26 filtered ports
PORT     STATE SERVICE
3000/tcp open  ppp
5432/tcp open  postgresql
9000/tcp open  cslistener
9200/tcp open  wap-wsp

When I shut down my rails server on port 3000, that entry goes from nmap

What is my mac address?

$ ifconfig

Then find the ether key for your connection

en0: ....
    ether cd:a2:01:51:0b:8a

My mac address is cd:a2:01:51:0b:8a

How can I access my Rails server on localhost:3000 from outside my home network?

  1. First set up my computer to have a static private IP within the network. Its address should not be dynamically assigned with DCHP (since a moving target would be too hard to deal with). As such, I would tell my router that mac address should forever be associated with a private IP address, e.g. '192.168.2.107',

  2. Go into the router and go to "Port Forwarding"

  3. Enter in my public ip address (as seen on the computer with the Rails server running)

  4. Now map an external port to the internal one (3000). These can be the same or different numbers.

References