ipinfo.ioとGoogleMapsAPIを組み合わせてIPアドレスから住所を表示するスクリプト

#!/bin/sh

IP=$1

if [ "$IP" = ""  ]; then
    echo "usage: $0 {ip address}"
    exit 1
fi


LATLNG=`curl -s ipinfo.io/${IP}/loc`

ADDR=`curl -s http://maps.googleapis.com/maps/api/geocode/json?latlng=${LATLNG}\&language=ja | grep formatted_address | head -n2 | tail -1 | cut -f4 -d'"'`

if [ ! -n "${ADDR}" ]; then
        ADDR=`curl -s http://maps.googleapis.com/maps/api/geocode/json?latlng=${LATLNG} | grep formatted_address | head -n1  | cut -f4 -d'"'`
fi

if [ -n "${ADDR}" ]; then
    echo "${ADDR}"
else
        COUNTRY_CODE=`curl -s ipinfo.io/${IP}/country`
        echo "${COUNTRY_CODE}"
fi