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

Retrieve network info from the command line Network
I found myself wanting to conveniently retrieve useful network information for my wired (en0) and wireless (en1) interfaces without having to open the Network System Preference panel, so I wrote a shell script to extract and format this information.

Just paste the following into your favorite text editor and save it as a shell script (e.g. getnet.sh), preferably somewhere in your $PATH. After you've saved it make sure it is executable by running chmod 0755 /path/to/getnet.sh from the Terminal.
#! /bin/bash

QUERY0="$(ipconfig getpacket en0)";
QUERY1="$(ipconfig getpacket en1)";
MAC0="$(ifconfig en0 | grep ether | awk '{print $2}')";
MAC1="$(ifconfig en1 | grep ether | awk '{print $2}')";

echo $QUERY0 | grep 'BOOTREPLY' > /dev/null;
ET=$?;

echo $QUERY1 | grep 'BOOTREPLY' > /dev/null;
WI=$?;

echo " ";

if [ $ET -eq 0 ] || [ $WI -eq 0 ]
 then
  PUBLIC="$(curl -s http://checkip.dyndns.org | awk '{print $6}' | awk 'BEGIN {FS = "<"} {print $1}')";
  echo "   Public IP: $PUBLIC";
fi;

echo "   Hostname: $HOSTNAME";
echo " ";

echo "Wired Ethernet (en0)";
echo "-----------------------";

if [ $ET -eq 0 ]
 then
  echo $QUERY0 | grep 'yiaddr = 0.0.0.0' > /dev/null;
  AT=$?;
  if [ $AT -eq 0 ]
   then
    IP="$(echo $QUERY0 | sed 's/.*ciaddr = \([[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\).*/\1 (Static)/')";
   else
    IP="$(echo $QUERY0 | sed 's/.*yiaddr = \([[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\).*/\1 (DHCP)/')";
  fi;
  SUBNET="$(echo $QUERY0 | sed 's/.*subnet_mask (ip): \([[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\).*/\1/')";
  ROUTER="$(echo $QUERY0 | sed 's/.*router (ip_mult): {\([^}]*\)}.*/\1/')";
  DNS="$(echo $QUERY0 | sed 's/.*domain_name_server (ip_mult): {\([^}]*\)}.*/\1/')";
  SEARCH="$(echo $QUERY0 | sed 's/.*domain_name (string): \(.*\) [[:alpha:]].*/\1/')";
  SPEED="$(ifconfig en0 | grep media: | sed 's/.*(//' | sed 's/ .*//' | sed 's/baseT/ MBit\/s/')";
  echo "  IP Address: $IP";
  echo "  Subnet Mask: $SUBNET";
  echo "    Router: $ROUTER";
  echo "  DNS Server: $DNS";
  echo "Search Domains: $SEARCH";
  echo "  MAC Address: $MAC0";
  echo "     Speed: $SPEED";
elif ! [ $ET -eq 0 ]
 then
  echo "  IP Address: inactive";
  echo "  MAC Address: $MAC0";
fi;

echo " ";
echo "Wireless Ethernet (en1)";
echo "-----------------------";

if [ $WI -eq 0 ]
 then
  echo $QUERY1 | grep 'yiaddr = 0.0.0.0' > /dev/null;
  AT=$?;
  if [ $AT -eq 0 ]
   then
    IP="$(echo $QUERY1 | sed 's/.*ciaddr = \([[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\).*/\1 (Static)/')";
   else
    IP="$(echo $QUERY1 | sed 's/.*yiaddr = \([[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\).*/\1 (DHCP)/')";
  fi;
  SUBNET="$(echo $QUERY1 | sed 's/.*subnet_mask (ip): \([[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\).*/\1/')";
  ROUTER="$(echo $QUERY1 | sed 's/.*router (ip_mult): {\([^}]*\)}.*/\1/')";
  DNS="$(echo $QUERY1 | sed 's/.*domain_name_server (ip_mult): {\([^}]*\)}.*/\1/')";
  SEARCH="$(echo $QUERY1 | sed 's/.*domain_name (string): \(.*\) [[:alpha:]].*/\1/')";
  SPEED="$(/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -I | grep lastTxRate: | sed 's/.*: //' | sed 's/$/ MBit\/s/')";
  echo "  IP Address: $IP";
  echo "  Subnet Mask: $SUBNET";
  echo "    Router: $ROUTER";
  echo "  DNS Server: $DNS";
  echo "Search Domains: $SEARCH";
  echo "  MAC Address: $MAC1";
  echo "     Speed: $SPEED"
elif ! [ $WI -eq 0 ]
 then
  echo "  IP Address: inactive";
  echo "  MAC Address: $MAC1";
fi;

echo " ";


Here is an example of the output from the script:
Public IP: 123.456.78.90
Hostname: CWB-MacBook.local
 
Wired Ethernet (en0)
-----------------------
IP Address: inactive
MAC Address: aa:bb:cc:dd:ee:ff
 
Wireless Ethernet (en1)
-----------------------
IP Address: 192.168.0.196 (DHCP)
Subnet Mask: 255.255.255.0
Router: 192.168.0.1
DNS Server: 192.168.0.1
Search Domains: woh.rr.com
MAC Address: 00:11:22:33:44:55
Speed: 117 MBit/s
[crarko adds: I tested this, and it works as described. You could also generate and parse a report from the system_profiler command if you are fluent with that utility.]
    •    
  • Currently 2.54 / 5
  You rated: 3 / 5 (24 votes cast)
 
[26,079 views]  

Retrieve network info from the command line | 16 comments | Create New Account
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: Tomnibus on Jun 17, '10 08:01:40AM

I wonder if this works with statically defined interfaces?

I'm connected with a Macbook Pro and I have the wired interface (en0) plugged in with a static IP. I copy/pasted this script and it tells me the Wired Interface is inactive like the example.

I notice it's getting the information from this command: ipconfig getpacket en0

I run that in the command line and there is no output. Whereas en1 shows the wireless information.



[ Reply to This | # ]
Retrieve network info from the command line
Authored by: feyd.rm on Jun 17, '10 03:02:33PM
The getpacket option is actually showing you the DHCP or BOOTP information from the packet that the computer accepted. If you are assigning the IP manually it makes sense that you are not seeing it.
$ man ipconfig


[ Reply to This | # ]
Retrieve network info from the command line
Authored by: victic on Jun 18, '10 10:35:57AM
Yes, the branch of code written for static address might benefit from a few changes. For example, the way I can retrieve my own IP when it's static is:
ifconfig en0 | grep inet | awk '{print $2}'

[ Reply to This | # ]
Retrieve network info from the command line
Authored by: metiure on Jun 17, '10 08:40:28AM

Excellent! Another geeklet for my GeekTools!



[ Reply to This | # ]
Retrieve network info from the command line
Authored by: exu on Jun 17, '10 09:10:33AM

Exactly what I was thinking.



[ Reply to This | # ]
Retrieve network info from the command line
Authored by: satcomer on Jun 17, '10 09:18:00AM

I guess I am good enough to edit the script because on my Mac Pro I have en0, en1 as wired and en2 as wireless. If some could help me edit for this extra port I would appreciate it.

Edited on Jun 17, '10 09:19:50AM by satcomer



[ Reply to This | # ]
Retrieve network info from the command line
Authored by: babbage on Jun 17, '10 10:11:24AM

Right -- this script assumes two Ethernet ports: one wired, one wireless. It doesn't attempt to handle the case of a Mac Pro or G5 with twin Ethernet ports, nor does it attempt to handle alternate custom ports such as a 10-gigabit Ethernet PCI card, multi-port 1-gigabit Ethernet cards, USB network adapters, etc.

For that matter, it's possible to set up standard TCP/IP networking over the Firewire port[s], though almost no one does that, but it would be nice to account for it just in case someone is using them. Likewise, if you have Parallels or VMWare Fusion installed, they can set up virtual interfaces that you might want to know about.

This script is an excellent starting point, but a more general solution to this would attempt to enumerate all of the current ports (by scanning the output of `networksetup -listallhardwareports`, for example), then go from there. I might tinker with it a bit & post back if I come up with anything useful.

--
DO NOT LEAVE IT IS NOT REAL

---

--
DO NOT LEAVE IT IS NOT REAL
Edited on Jun 17, '10 10:53:07AM by babbage


[ Reply to This | # ]
Non-CLI option
Authored by: kiltbear on Jun 17, '10 09:30:34AM
For those who don't want to go the command line route, but would still like this information easily available in the menu bar, there is the ever useful MenuMeters. It has some extra information than this script and is missing some information.
Edited on Jun 17, '10 09:32:08AM by kiltbear


[ Reply to This | # ]
Retrieve network info from the command line
Authored by: ambrose on Jun 17, '10 12:02:39PM
There is a command-line configuration tool called networksetup which acts as an interface to the Network Panel of the System Preferences app. It's not capable of providing all the information obearsstate's script does, but it does present a some of it, with the advantage of cutting down on the need for variable assignments and stream editing. It also offers other information some may find useful. As always, the man pages are the place to go, but just to whet the appetites of those who care about such things, here's a partial list of networksetup's command flags:

[-listnetworkserviceorder]

[-listallnetworkservices]

[-listallhardwareports]

[-detectnewhardware]

[-getmacaddress hardwareport]

[-getcomputername]

[-getdnsservers networkservice]

[-getsearchdomains networkservice]

[-getwebproxy networkservice]

[-getstreamingproxy networkservice]

[-getairportnetwork]

[-getairportpower]

[-getnetworkserviceenabled networkservice]

[-createnetworkservice hardwareport]

[-ordernetworkservices service1 [service2] [service3] [...]]

[-getMTU hardwareport]

[-getmedia hardwareport]

[-listvalidmedia hardwareport]

[-listdevicesthatsupportVLAN]

In cases where it is possible, the commands are able to set preferences as well as get them. (FWIW, there's another useful System Preferences command-lne tool called systemsetup. I think it's at least worth a look.

[ Reply to This | # ]

Retrieve network info from the command line
Authored by: feyd.rm on Jun 17, '10 03:06:52PM
Agreed if you are dealing with Mac Pros or MacBook Airs,
$ networksetp -listallhardwareports
can give you a better picture of what is going on.

[ Reply to This | # ]
Retrieve network info from the command line
Authored by: dzurn on Jun 29, '10 03:51:29PM
Missing a "u". Should be:

$ networksetup -listallhardwareports

---
Madness takes its toll.
Please have exact change.


[ Reply to This | # ]
Retrieve network info from the command line
Authored by: victic on Jun 18, '10 10:39:42AM

Great script! I really enjoyed reading it, thank you.

However, the branch of code that refers to the case of static IP works incorrectly: it states that interface is inactive, when IP was set manually.



[ Reply to This | # ]
Retrieve network info from the command line
Authored by: encro on Jun 22, '10 02:13:36AM
To show your external public (WAN) IP use: dns-sd -X

The method provided above will provide your external IP from your router via NAT-PMP.

You will need to massage the output a little to reduce it to just the IP address.

---
Steve


[ Reply to This | # ]
Retrieve network info from the command line
Authored by: srogers4 on Jun 22, '10 07:54:34AM

Or you could install iStat Nano and then click on the Dashboard icon in the dock when you want to know that stuff. Less geeky, but effective.



[ Reply to This | # ]
Retrieve network info from the command line
Authored by: ehunt123 on Jun 23, '10 05:44:11AM

For those who want something more customized/not a script (and usually faster), the SystemConfiguration
framework has been around and documented since 10.4 (at least 10.5). A few tools and some opensource code are scattered out there for performing things like changing proxies, etc.



[ Reply to This | # ]
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 | # ]