Programmatically determine your machine’s gateway IP address

One of the most popular destinations network engineers tend to ping to understand their network connectivity is Google’s 8.8.8.8 address.

That works great to get a sense for your latency and connectivity to Google, but you’ll also want to ping your router. This way if your ISP is the problem, your pings to 8.8.8.8 will fail but the ping to your router will be unaffected. Similarly if you’re having issues reaching your router, it would be waste of time to call your ISP (usually it’s a waste of time to call your ISP anyways but you get my point).

How do we do this in an automated way?

Because we’re focused on automating and removing complexity from Wifi troubleshooting, we need our application to be able to quickly and reliably determine the IP address of the local router (also known as the gateway IP).

We found a few suggestion on how to do this, but none of them felt quite right. In the end we decided that parsing the router’s IP address from traceroute output was the simplest, most reliable solution. traceroute comes pre-installed on Mac OS and most linux distributions and the router IP seems to reliably appear as the first hop.

Here’s how we did it:

~$ gateway_ip=$(traceroute 8.8.8.8 2>&1 | head -2 | tail -1 | perl -pe 's/.*\((.*)?\).*/$1/g')

What’s happening here?

First we traceroute to our favorite IP address, 8.8.8.8. Because traceroute sends its output to stderr, we redirect stderr to stdout so that we can pipe it to additional commands.

~$ traceroute 8.8.8.8 2>&1

We only want the first hop from the traceroute output. That’s our gateway IP so we head the first two lines and tail the last one.

~$ traceroute 8.8.8.8 2>&1 | head -2 | tail -1

You can run this command and you’ll see the one line of traceroute output containing our router’s IP address:

~$ traceroute 8.8.8.8 2>&1 | head -2 | tail -1
 1  router (192.168.3.1)  1.793 ms  1.707 ms  3.030 ms

Lastly we need to pull out the IP address. We use perl and regex to get the job done:

~$ traceroute 8.8.8.8 2>&1 | head -2 | tail -1 | perl -pe 's/.*\((.*)?\).*/$1/g'
192.168.3.1

Hope this was helpful. We’d love to hear of more reliable ways to do this!

JOIN NOW, SPACE IS LIMITED

Ready to fix your Wifi for good?