#!/bin/sh iprx='^([0-9]+\.){3}[0-9]+$' valid() { echo "$1" | egrep -q "$iprx"; } vote() { sort | uniq -c | sort -nr | head -1 | sed 's/^ *[0-9]\+ \+//'; } get_dep() { dep=$1 [ "$(dpkg-query -s "$dep"|sed -ne 's/^Status: //p')" = "install ok installed" ] || sudo apt-get install "$dep" >&2 } # urls from http://www.linuxquestions.org/questions/linux-networking-3/how-can-i-get-my-external-ip-address-from-behind-a-nat-333878/ websites='http://showip.codebrainz.ca/ http://www.whatismyip.com/automation/n09230945.asp http://www.showmyip.com/simple/ http://cfaj.freeshell.org/ipaddr.cgi https://secure.informaction.com/ipecho/ http://icanhazip.com/' websites() { get_dep curl timeout=2 for ws in $websites; do ip=$(curl -s -m $timeout "$ws"|head -1) valid "$ip" && echo $ip || echo "failed to get ip from $ws" >&2 done } stunserver_org() { get_dep stun stun -v stunserver.org 1 2>&1|sed -ne 's/^MappedAddress *= *//p'|head -n1|cut -d: -f1; } dyndns_org() { get_dep curl curl -m 5 -s http://checkip.dyndns.org/|sed -ne 's/.*Current IP Address: *\(\([0-9]\+\.\)\{3\}[0-9]\+\).*/\1/p'; } ip() { for cmd in websites stunserver_org dyndns_org; do $cmd done | egrep "$iprx" | vote } ip=$(ip) valid "$ip" && { echo $ip; exit; } echo 'could not find ip' >&2; exit 1;