Skip to content

Instantly share code, notes, and snippets.

@kbingham
Created August 21, 2015 14:10
Show Gist options
  • Save kbingham/69e2a7b7c0fccec6cb69 to your computer and use it in GitHub Desktop.
Save kbingham/69e2a7b7c0fccec6cb69 to your computer and use it in GitHub Desktop.
#!/bin/sh
### WIMIP
### A helper script to easily report both local and public IP addresses of a device on commandline
### Kieran Bingham 2015
### www.kieranbingham.co.uk
IFACE=`route -n | grep ^0.0.0.0 | awk '{ print $8 }'`
show_help() {
cat << EOF
Usage: ${0##*/} [-hlpq] [iface]
What Is My IP? ... I'm glad you asked.
-h display this help and exit
-l display locally native IP address based on current default routing
-p display publicly visible, external IP address
-q act quietly ... just print IP addresses without 'prompts'
iface display IP address of iface (Default $IFACE) (implies act quietly)
EOF
}
# Default to displaying 'useful' information
quiet=echo
native_ip=yes
public_ip=yes
# Scripts can call with options to get specific information
OPTIND=1
while getopts "hlpq" opt; do
case "$opt" in
h)
show_help
exit 0
;;
l) native_ip=yes
public_ip=no
quiet=true
;;
p) public_ip=yes
native_ip=no
quiet=true
;;
q) quiet=true
;;
'?')
show_help >&2
exit 1
;;
esac
done
shift "$((OPTIND-1))" # Shift off the options and optional --.
# Deal with optionally specified interface
if [ $1 ]
then
IFACE=${1:-$IFACE}
quiet=true
native_ip=yes
public_ip=no
fi
# Discover some addresses
NATIVE_IP=`ifconfig $IFACE | sed -r -e '/.*inet\s*(addr:)*(([0-9]{1,3}\.){3}[0-9]{1,3}).*/!d;s//\2/'`
PUBLIC_IP=`dig +short myip.opendns.com @resolver1.opendns.com`
# V2. Display all IP addresses: ifconfig | sed -r -e '/.*inet\s*(addr:)*(([0-9]{1,3}\.){3}[0-9]{1,3}).*/!d;s//\2/';
if [ "$native_ip" = yes ]
then
$quiet -n "$IFACE: "
echo $NATIVE_IP
fi
if [ "$public_ip" = yes ]
then
$quiet -n "public: "
echo $PUBLIC_IP
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment