BASH – Router’s Public IP Address For Mac

Why This Script?

While in its simplest form of usage, this script will only print out the public (& private) IP address along with the SSID to which the machine is connected to, the results therefrom can be used for a variety of other purposes – I will let your imagination fly you to your dream destination!


The Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#! /bin/bash
 
# BASH script to display the IP Address - one that the machine has, 
# as well as router's public IP Address, if any.
# Tested on Apple Mac Snow Leopard 10.6.2
 
# First written : Gowtham, Thu Dec 31 12:05:35 EST 2005
# Last modified : Gowtham, Thu Dec 31 12:05:35 EST 2005
 
# en1 is the wireless interface. 
# Change appropriately, if different
export WIFI_INTERFACE="en1"
 
# Details about the ${WIFI_INTERFACE}
ifconfig ${WIFI_INTERFACE} > public_ip.txt
export STATUS=`cat public_ip.txt | grep "status" | awk '{print $4}'`
 
# Analyze the details and display appropriate information
if [ "$STATUS" = "active" ];
then
  export IPADDRESS=`cat public_ip.txt | grep broadcast | awk '{print $2}'`
  export SSID=`system_profiler SPAirPortDataType | \
               grep -A1 "Current Network Information:" | \
               tail -1 | awk -F ':' '{print $1}' | \
               sed 's/^[ \t]*//;s/[ \t]*$//'`
else
  echo
  echo " `date`"
  echo " You are not connected to the internet"
  echo
  exit 0
fi
 
# Get the public IP address, $NSIP
export NSIP=`curl -s http://checkip.dyndns.org | awk '{print $6}' | \
             awk -F '<' '{print $1}'`
 
# Compare $IPADDRESS & $NSIP
# Display appropriate information along with SSID
if [ "$IPADDRESS" = "$NSIP" ];
then
  echo
  echo "  `date`"
  echo "  SSID       : $SSID"
  echo "  IP Address : $IPADDRESS"
  echo
else
  echo
  echo "  `date`"
  echo "  SSID                        : $SSID"
  echo "  Machine's static IP Address : $IPADDRESS"
  echo "  Router's  public IP Address : $NSIP"
  echo
fi
 
# Delete the scratch file
rm -f public_ip.txt


Screenshots



Direct connection to the internet

Directly connected to the internet


Configured behind a router

Configured behind a router



I must thank Jon DeVree [@nuxi] for help with a previous version of this script [for linux] as well as Sarah for graciously letting me use her WiFi network.

One Reply to “BASH – Router’s Public IP Address For Mac”

Comments are closed.