I really, really should stop scripting in VBscript. It is boo, boo and is already 10+ years replaced by Powershell. Having said that, I needed a simple method to detect a change on a dynamic assigned public IP address.
Note: for the SendMail function check this post.
This is the script:
on error resume next
dim fso, wsh
set fso = Createobject("scripting.filesystemobject")
set wsh = CreateObject("wscript.shell")
const key = "HKEY_CURRENT_USER\SOFTWARE\getPublicIP\publicIPaddress"
if isnull(wsh.regRead(key)) then wsh.Regwrite key,"0.0.0.0", "REG_SZ"
Err.Clear
'--- Get public IP address...
Set objHTTP = CreateObject("Msxml2.XMLHTTP")
objHTTP.open "GET", "http://ipinfo.io/json", False
objHTTP.send
t = split(Cstr(objHTTP.responseText),chr(34))
currentIPaddress = t(3)
'--- Read previous IP address...
previousIPaddress = wsh.regRead(key)
'--- Compare and when changed, send email with new IP address...
if currentIPaddress <> previousIPaddress then
s = "Public IP address has changed." & vbCrLF
s = s & "Previous IP address: " & previousIPaddress & vbCrLf
s = s & "Current IP address : " & currentIPaddress & vbCrLf
wscript.echo "Sending email:" &vbCrLf & s
if sendmail(s) = 0 then
wscript.echo "*** Succesfully sent email."
wsh.Regwrite key, currentIPaddress, "REG_SZ"
wsh.LogEvent 0,s
else
wscript.echo "*** Error sending email"
end if
else
wscript.echo "*** Public IP address not changed: " & currentIPaddress
end if