Determining currently used NIC on CLI

command lineNetwork

I do a lot of work on Virtual Machines, and have several scripts to help me configure them quickly. I could fully automate spinning up a headless VM, except that I need to know the IP of my host machine for configuring VNC stuff.

I use either of the following two commands to get the current IP address:

ipconfig getifaddr en1      # For IP address assigned to wireless
ipconfig getifaddr en0      # For IP address assigned to ethernet

The problem is that I have to tell my script whether to use en0 or en1. I use wireless at home and ethernet at work, so I can't make an assumption.

I could use:

ifconfig | grep '192'

and parse the resulting line (both work and home assign class C addresses), but I'd rather not have to do that.

Is there a way to determine which NIC is currently connected to the network from the command line? Or at least a better way of determining the host IP?

My machine uses Mountain Lion, if that's relevant.

Best Answer

I would think your problem is determining "service order." The basic magic you see happen in the System Preferences > Network where the highest ranking connected service sorts to the top.

This Mac OS Hints article discusses a similar problem and solution.