I do lots of WiFi lab work using my MacBook PRO. IP addresses keep changing and the easiest way for me to display my current IP is to launch a terminal session and type the command: ifconfig -a. You can also use MacBook's system preferences > network > select your airport adapter > click advanced > click TCP/IP tab. But this is kind of tedious.
The ifconfig command will actually list all interfaces and their corresponding IP addresses, if configured. To get rid of the clutter, I use the ifconfig en1 command, which simply lists my WiFi interface, as follows:
ifconfig en1
en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether 58:b0:35:6a:61:be
inet 192.168.1.101 netmask 0xffffff00 broadcast 192.168.1.255
media: autoselect
status: active
This results in a 5 line output, which is too much. All I need is the IP address field. Let's refine this with the following command:
ifconfig en1 | grep inet
inet 192.168.1.101 netmask 0xffffff00 broadcast 192.168.1.255
This time, it only displayed the third line, looks good, but not enough. Lets print the IP address only:
ifconfig en1 | grep inet | cut -d " " -f2
192.168.1.101
You noticed the cut command uses a space as delimiter (-d " ") and prints field number 2 (-f2)
Now the fun part, let's use the watch command to dynamically display the WiFi interface IP address:
watch -d2 'ifconfig en1 | grep inet | cut -d" " -f2'
After you execute this command, your terminal session display will clear and only display IP address updates every 2 seconds. (parameter -d2). If we take this one step further, you can create an alias to invoke this command when needed. Here is an alias called ipwatch that I stored in my .bashrc file:
alias ipwatch="watch -d2 'ifconfig en1 | grep inet | cut -d\" \" -f2'"
You probably noticed that I added backslashes before the double quotes after the cut command. This is to prevent shell expansion. Now, all you have to do is to type ipwatch and watch you IP address updating dynamically.
If you do not have the watch command installed in your MAC OS X system, you can add it using MacPorts. In a previous blog I describe how to install MacPorts on your MacBook. Just make sure you download the latest MacPorts version for your platform.
As an alternative, if you do not want to install MacPorts, you can create a loop in your terminal session with the while command. Here is an example
while ifconfig en1 | grep inet | cut -d" " -f2; do sleep 2; done
Use the following ipwatch alias form in you .bashrc file:
alias ipwatch="while ifconfig en1 | grep inet | cut -d\" \" -f2; do sleep 2; done"
Whenever you type ipwatch, your WiFi IP will display every 2 seconds, 1 per line. Hit control-c to stop.
Conclusion
Dynamically displaying your WiFi IP address from a terminal shell command line is easy and efficient. Using shell aliases can help simplify this task further.