Thursday, October 20, 2011

getting an ip address

I sometimes need to know my local IP address for sharing data on my local network.
here is a oneliner that does the trick:


grep ":" /proc/net/arp |awk '{print $1}'
And a faster way as a function using only shell builtins:
get_ip(){
while read A || [ "${A}" ]; do
    case "${A}" in
        [0-9]*)
            echo "${A%% *}"
        ;;
    esac
done </proc/net/arp
}
The second one seems like it would be slower, because it is more code.  Right?  Not really, when you account for grep and awk as "code".  They take a not-insignificant time to be found, load and then run, but lets be honest, you won't notice this if you are running it by itself from a prompt.  It could however come in handy in speeding up a boot process on a connected device.


But what if we have a local dynamic ip address and want to know what our "real" ip address is.
Kieth Hatfield has posted a server side php script and shell script to do just that here:
http://www.keithscode.com/blog-items/wan-ip-from-a-bash-script.html

the server side php is pretty simple:
<?php echo $_SERVER['REMOTE_ADDR']; ?>
 and the shell script is:
wget -q -O - http://some.url.com 2>/dev/null
 (Note: Keith's demo is at http://ip.keithscode.com)
 There are several other places to get this information such as:
http://automation.whatismyip.com/n09230945.asp    (NOTE: once every 300 seconds)
checkip.dyndns.org (NOTE: has html formatting)

No comments:

Post a Comment