Programatically Getting IP Address on the MacBook Air
(It’s tougher than you think.)
Obtaining the IP address on a desktop Mac with built-in ethernet ports is relatively straightforward. You can rely on en0 existing and the connection being stable. On desktops, TCP connections are maintained, even in a “CLOSE_WAIT” state:
(IP addresses changed to protect the guilty)# netstat -p tcp Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 192.118.156.212.62146 a192-17-157-46.zz.https SYN_SENT tcp4 0 0 192.118.156.212.62145 192.69.245.140.https ESTABLISHED tcp4 0 0 192.118.156.212.62106 my.server..micro ESTABLISHED tcp4 0 0 192.118.156.212.60876 192.70.186.139.sip-tls ESTABLISHED tcp4 0 0 192.118.156.212.net-as 192.29.231.207.61415 ESTABLISHED tcp4 0 0 192.118.156.212.net-as 192.29.231.207.61414 ESTABLISHED tcp4 0 0 192.118.156.212.49273 proxy.net.pcsyn CLOSE_WAIT tcp4 0 0 192.118.156.212.49272 proxy.net.pcsyn CLOSE_WAIT
However, the MacBook Air has no built-in ethernet. To hardwire one to a network, a USB<->Ethernet transceiver must be added on. And in an effort to save power, the Air drops any unused connections after 5 seconds. Witness:
# netstat -p tcp Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 192.118.156.212.62145 192.69.245.140.https ESTABLISHED tcp4 0 0 192.118.156.212.net-as 192.29.231.207.61415 ESTABLISHED tcp4 0 0 192.118.156.212.net-as 192.29.231.207.61414 ESTABLISHED
After a few seconds the very same command yields zilch:
# netstat -p tcp #
So any scripts you write to grab the IP address that use netstat (the preferred method you’ll find recommended by almost all sites if you Google the topic) will yield a blank result.
You could activate the TCP connection by launching Safari or issuing a curl command and quickly reading netstat’s output within 5 seconds, but that’s a kludge.
The better answer? Good old ifconfig, which will yield the persistent IP state of the Mac no matter how long the network connections have been idle. On the same Air as above where netstat was reporting no info, you get this:
# ifconfig | grep "broadcast" inet 192.118.156.212 netmask 0xffffff00 broadcast 192.118.156.255
Ding! (note that we limited the search to lines containing “broadcast” to prevent finding the loopback and other ports irrelevant to our current need.)
To complete the search for a usable IP, we just:
#ip=`ifconfig | grep "broadcast" | cut -d " " -f2` #echo $ip 192.118.156.212
Now you have $ip waiting for you to act on. Examples:
if [ "$ip" = "" ]; then echo "No ethernet cable appears to be plugged in." fi
Or
if [ "${ip:0:7}" = "169.254" ]; then echo "No DHCP server was found." fi
Have fun!