Notification of changed dynamic (public) IP address
- Get my public IP address?
- Get my private (local) IP address?
- If the IP address has changed since the last reading, record the new value with a timestamp
- Put this in a script; the argument will specify public or private
- Put the script in a function, and place the function in .profile
- Send notification of IP address changes to designated party via a) Apple iMessage, or b) GMail using Python.
- My public IP address is the IP that a remote host will see when you connect from behind your firewall/router/NAT. Following are known sources that will return your public IP address, and the method for extracting the IP address from the reply:
Sources of IP address information:
- http://whatismijnip.nl :
curl -s http://whatismijnip.nl | cut -d " " -f 5
- http://whatismyip.akamai.com/ :
curl -s http://whatismyip.akamai.com/ && echo
2 - https://www.whatsmyip.org/
- https://www.whatismypublicip.com/
- http://ipecho.net/plain :
curl -s -w "\n" http://ipecho.net/plain
2 - https://ifconfig.me/ :
curl ifconfig.me && echo
- My private IP address is best obtained from
ip
.ip
is current, maintained, and perhaps most importantly for scripting purposes, it produces a consistent & parsable output. In particular,ip route
works on hosts with single or multiple interfaces, and/or route specifications. :
$ ip route get 8.8.8.8 | awk '{ print $7; exit }'
-
We'll use a file named
watchip.sh.csv
as a database to save our results, and keep a log of when we detect IP address changes. We won't make an entry in the file unless there has been a change. We will record a change by appending the new IP address and a timestamp of our file. -
Read the last IP address in the out file as follows:
lastip=$( tail -n 1 ~/watchip.sh.csv) # NOTE: need awk to get IPADDR, not time
- Get the time of the reading. Use Unix time to remove localization, and make diffs easier to calculate.
date +"%s
- We'll use the "flags method" in
bash
. This will give us the ability to request either internal or external IP addr, and we'll get both if no argument is passed. :
REFERENCES/NOTES:
-
How can I get my external IP address in a shell script? (See the final answer at the bottom of this page)
-
&& echo
and thecurl
option-w "\n"
accomplish the same purpose: add a newline to thecurl
output. This may be useful at the command line for example, but perhaps not everywhere. -
These are good candidates for function declarations in
~/.profile
; for example:function externalip () { curl http://ipecho.net/plain; echo; }
-
How to Pass Arguments to a Bash Script : Lifewire article; good explanation, but no good code samples
-
How to get arguments with flags in Bash : Good sample code fragments
-
Parsing command line arguments in
bash
: How to process the arguments; appears fairly comprehensive -
A
getopts
tutorial Required reading