Skip to content

Instantly share code, notes, and snippets.

@syaau
Last active February 26, 2017 17:56
Show Gist options
  • Save syaau/51fb07d02245efba9627e1d7c3f96483 to your computer and use it in GitHub Desktop.
Save syaau/51fb07d02245efba9627e1d7c3f96483 to your computer and use it in GitHub Desktop.
Simple script for getting geo information from ip or host name
#!/bin/sh
# Simple script for getting geo information from ip or host name.
# This script uses linux command `host` to get ip address for
# the given domain name. It also depends on `http://ipinfo.io/`
# to get the geo information.
#
# The valid_ip function has been copied directly from
# http://www.linuxjournal.com/content/validating-ip-address-bash-script
#
# INSTALLATION
# Save as /usr/local/bin/ipinfo
# chmod u+x /usr/local/bin/ipinfo
#
# USAGE
# ipinfo <ip>
# ipinfo <domain>
# ipinfo bhoos.com
# ipinfo 54.230.190.68
#
# Test an IP address for validity:
# Usage:
# valid_ip IP_ADDRESS
# if [[ $? -eq 0 ]]; then echo good; else echo bad; fi
# OR
# if valid_ip IP_ADDRESS; then echo good; else echo bad; fi
#
function valid_ip()
{
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
# Store the argument for using later
ARG=$1
if valid_ip $ARG; then
curl ipinfo.io/$ARG
else
IP=$(host $ARG | awk '/has address/ { print $4 ; exit }')
if [ "" == "$IP" ]; then
echo "$ARG could not be resolved"
else
curl ipinfo.io/$IP
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment