Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!


Click here to return to the 'Retrieve network info from the command line' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Retrieve network info from the command line
Authored by: dgerrity on Jan 20, '11 03:19:04PM
Regarding interface names, I find it helpful to list the network services available (that is, the names the user configures in System Preferences) and then associate them with an interface. I run the setup code in my .bash_profile. My scripts can then reference ${AirPort} to get en1 (on my system), or iterate through the list of active interfaces to obtain relevant data for the OS X Network Location in use. This method has an additional benefit in that the interfaces are listed in priority order so you know which interface is getting tried first. Here is some code that accomplishes that:

# Get the list of network devices and their corresponding interfaces in
# service order priority.  The sed commands at the end first extract
# the names of the devices and their corresponding interface names,
# then the remove illegal characters and replace them with "_".
# The export is optional depending on whether you'd like these
# definitions in your shell or not (I have it in .bash_profile)
export devlist="$(networksetup -listnetworkserviceorder | grep Hardware | \
    sed -e 's/^(H.*rt: \(.*\), Device: \(.*\))/\1/' \
        -e 's/[()\*#]//g' -e 's/[ -]/_/g')"

echo My device list:
for dev in ${devlist}; do echo ${dev}; done
echo

iflist="$(networksetup -listnetworkserviceorder | grep Hardware | \
    sed -e 's/^(H.*rt: \(.*\), Device: \(.*\))/\1=\2/' \
        -e 's/[()\*#]//g' -e 's/[ -]/_/g')"

echo My interfaces:
for iface in ${iflist}; do
    eval export ${iface}
    echo ${iface}
done
echo

echo AirPort is on ${AirPort}   # Probably en1 depending on your system        
echo

# The original tip could be implemented inside a for loop like this:
# (the bang in the environment variable does an indirect lookup)
for dev in ${devlist}; do
    echo "${dev} on ${!dev}"
    echo ----------------------
    ifconfig -m ${!dev} | grep "inet " | awk '{print $2'}
    echo etc....
    echo
done
If you implement this in a Geeklet, you may have to source your bash_profile or copy the code into the Geeklet script as the .bash_profile is only read on a login invocation.

[ Reply to This | # ]