Theresa O’Connor

Two trivial lifehacks

Two stupid Unix scripts I find myself using surprisingly often.

Figuring out a Unix laptop's current IP address is more involved than you might imagine. For instance, consider my work laptop, a PowerBook running Mac OS X.

This laptop has 6 network interfaces (at least insofar as ifconfig(8) is concerned): lo0, gif0, stf0, en0, en1, and fw0. Now, it just so happens that en0 (wired connection) and en1 (AirPort) are the only interesting ones, but how are we to know that programmatically in a cross-platform way? And which one is the interesting one?

The trick is to look up, via the machine's routing table, which interface is used for the default route. Once we know that, we can check the IP address of that interface. Unfortunately, the output of programs such as netstat(1) and ifconfig(8) vary from Unix to Unix. Hence my ip script described below:

ip

Prints this machine's IP address. (Specifically, the IP address of the interface over which traffic will pass by default). Tested on Mac OS X, FreeBSD, Linux, OpenBSD, and Solaris.

Example usage:

ted in ~ on roisin's ttyp1 at 5:30pm
(h=1076, r=0): ip
192.168.1.176
dr

Prints the IP of this machine's default router. Tested on Mac OS X, FreeBSD, Linux, and Solaris.

Example usage:

ted in ~ on roisin's ttyp1 at 5:30pm
(h=1077, r=0): dr
192.168.1.1

I probably use these scripts several times a week.