WanIP Checker

Moderator: leecollings

Post Reply
User avatar
emme
Posts: 909
Joined: Monday 27 June 2016 11:02
Target OS: Raspberry Pi / ODroid
Domoticz version: latest
Location: Milano, Italy
Contact:

WanIP Checker

Post by emme »

Ciao,

Due to some requirements I have I've wrote a script to get and eventually update the Wan IP Address.

my provider use not to change the public IP unless the IAD at my home is resetted or remotely upgraded, but since I'm evaluating to remove the ddns and connect just using the externa IP, I was seeking for a way to obtain it.

So I've created a Variable named WanIP_IP and a script that trigger a bash command and do the rest...
here is it

Code: Select all

VARNAME = 'WanIP_IP'
GETIP = 'curl -s https://4.ifcfg.me/'
TMPFILE = '/home/pi/domoticz/scripts/wanip.txt'
PTPPREFIX = '>>> [WanIP checker] >>> '
IDLESECS = 21600 -- 6 hours

function timeDiff(dName)
    t1 = os.time()
    updTime = uservariables_lastupdate[dName]
    year = string.sub(updTime, 1, 4)
    month = string.sub(updTime, 6, 7)
    day = string.sub(updTime, 9, 10)
    hour = string.sub(updTime, 12, 13)
    minutes = string.sub(updTime, 15, 16)
    seconds = string.sub(updTime, 18, 19)
    
    t2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}
    
    tDiff = os.difftime(t1,t2)
    return tDiff
end

CURRWNIP = uservariables[VARNAME]
IDLETIME = tonumber(timeDiff(VARNAME))

commandArray = {}
    if IDLETIME > IDLESECS then
        os.execute(GETIP..' > '..TMPFILE)
        wanip = io.open(TMPFILE):read()
        
        if not wanip then
            print (PTPPREFIX..'impossibile reperire Wan IP') 
        else
            if wanip ~= CURRWNIP then
                print (PTPPREFIX..'Agiornamento WAN IP: '..wanip)
                commandArray['Variable:'..VARNAME] = wanip
                os.execute('rm /home/pi/domoticz/scripts/wanip.txt')
            end
        end
    end
return commandArray
It's a TIME:EVENT script and runs every 6 hours (set by IDLESEC), get the external IP, check for differences in case and eventually update
than I have a variable script that notify me the change via Telegram and email.

With many thanks to @egregius... I think in bash this can be done in this way:

Code: Select all

#!/bin/bash

LASTWANIP =`cat /tmp/lastwanip.txt` 
NEWWANIP = `curl -s https://4.ifcfg.me/`
if [[ $LASTWANIP -ne $NEWWANIP ]];then
   echo $NEWWANIP > /tmp/lasttemp.txt
   DOMOTICZ=`curl -s "http://127.0.0.1:8080/json.htm?type=command&param=updateuservariable&vname=WanIP_IP&vtype=string&vvalue=$NEWWANIP
fi
and it could be sets as a cron job
ciao
M
The most dangerous phrase in any language is:
"We always done this way"
User avatar
remb0
Posts: 499
Joined: Thursday 11 July 2013 22:21
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: The Netherlands
Contact:

Re: WanIP Checker

Post by remb0 »

Great work! can you add it to the wiki? same account as forum.
that way all info is saved in a central place.
User avatar
emme
Posts: 909
Joined: Monday 27 June 2016 11:02
Target OS: Raspberry Pi / ODroid
Domoticz version: latest
Location: Milano, Italy
Contact:

Re: WanIP Checker

Post by emme »

uh.. really?!
REALLY REALLY?!?! :shock: :o :mrgreen:

Will do this during the weekend (my office firewall blocks Domoticz Wiki :( )
The most dangerous phrase in any language is:
"We always done this way"
User avatar
remb0
Posts: 499
Joined: Thursday 11 July 2013 22:21
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: The Netherlands
Contact:

Re: WanIP Checker

Post by remb0 »

:) thanks!

I should look for another job :P one that allow domoticz sites :)
User avatar
Egregius
Posts: 2589
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: WanIP Checker

Post by Egregius »

You should ass something that sends you the new ip address. How will you now it if it's changed and you can't access domoticz anymore?
Great that you provide it in 2 languages!
I think it's better to use the shell version, what if the ip is changed and domoticz is crashed so it can't sent you anything? Then you don't have the external address to do anything.
User avatar
emme
Posts: 909
Joined: Monday 27 June 2016 11:02
Target OS: Raspberry Pi / ODroid
Domoticz version: latest
Location: Milano, Italy
Contact:

Re: WanIP Checker

Post by emme »

the IP event in domoticz is a time event, but triggers the check on 6 hour basis (it is setted by the IDLESECS local variable)
I have another Variable event that sends me the notification of the new IP (of the variable change)

The bash is intend to be a cron job and can run every hour and can be also include a sendmail command for notifying the change
The most dangerous phrase in any language is:
"We always done this way"
HM31
Posts: 56
Joined: Friday 04 August 2017 16:13
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: WanIP Checker

Post by HM31 »

Here is an adaptation to Domoticz installed on Synology (essentially the temp file has to be moved elsewhere ... and translation in French for messages ... not necessary but easier for me ! :lol: )

Code: Select all

VARNAME = 'WanIP_IP'
GETIP = 'curl -s https://4.ifcfg.me/'
TMPFILE = '/volume1/@appstore/domoticz/var/scripts/wanip.txt'
PTPPREFIX = '>>> [WanIP checker] >>> '
IDLESECS = 1800  -- 30 mn

function timeDiff(dName)
    t1 = os.time()
    updTime = uservariables_lastupdate[dName]
    year = string.sub(updTime, 1, 4)
    month = string.sub(updTime, 6, 7)
    day = string.sub(updTime, 9, 10)
    hour = string.sub(updTime, 12, 13)
    minutes = string.sub(updTime, 15, 16)
    seconds = string.sub(updTime, 18, 19)
   
    t2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}
   
    tDiff = os.difftime(t1,t2)
    return tDiff
end

CURRWNIP = uservariables[VARNAME]
IDLETIME = tonumber(timeDiff(VARNAME))

commandArray = {}
    if IDLETIME > IDLESECS then
        os.execute(GETIP..' > '..TMPFILE)
        wanip = io.open(TMPFILE):read()
       
        if not wanip then
            print (PTPPREFIX..'Impossible de récupérer WAN IP')
        else
            if wanip ~= CURRWNIP then
                print (PTPPREFIX..'Actualisation de WAN IP: '..wanip)
                commandArray['Variable:'..VARNAME] = wanip
                os.execute('rm /volume1/@appstore/domoticz/var/scripts/wanip.txt')
            end
        end
    end
return commandArray
Next step, updating a general, text dummy switch with the value, thus doing quite the same thing as this thread https://www.domoticz.com/forum/viewtopi ... 65&t=16266, that was initialy inspired by emme
User avatar
emme
Posts: 909
Joined: Monday 27 June 2016 11:02
Target OS: Raspberry Pi / ODroid
Domoticz version: latest
Location: Milano, Italy
Contact:

Re: WanIP Checker

Post by emme »

Ciao,

since my plugin won't work anymore, I've re-wrote the wanIP checker under dzVents:

Code: Select all

return {
	on = {
            timer = { 'every 6 hours' }
	},
	
	logging = {
            level = domoticz.LOG_FORCE,
            marker = '[WAN IP]'
    },

    execute = function(dz, devNil)
        local dzb      = dz.LOG_FORCE
        local getIp    = 'curl -s https://4.ifcfg.me/'
        local tmpFile  = '/home/pi/domoticz/scripts/wanip.txt'
        local actIp    = ''
        local devIp = dz.devices('Wan IP')
        local currIp = devIp.text
		
        os.execute(getIp..' > '..tmpFile)
        actIp = io.open(tmpFile):read()
        
        if actIp == nil then actIp = 'Impossibile recuperare IP' end 
        
        if actIp ~= currIp then
            msgTxt = 'Wan IP Cambiato: '..currIp..' ==> '..actIp
            dz.log(msgTxt, dzb)
            dz.notify('Wan IP', msgTxt, dz.PRIORITY_EMERGENCY)
            devIp.updateText(actIp)
            os.execute('rm '..tmpFile)
        else 
            dz.log('Nessuna variazione', dzb)
        end 
    end
}
you only have to create a dummy text switch and grab its name (plus, of course replace the italian sentences :P )
The most dangerous phrase in any language is:
"We always done this way"
rlschulz
Posts: 20
Joined: Sunday 25 October 2015 16:33
Target OS: Windows
Domoticz version: 3.5877
Contact:

Re: WanIP Checker

Post by rlschulz »

I attempted to write this for a windows OS and a little less Italian. :-)
So far I built a text switch and am trying to figure out how to get this to run.

Any help would be appreciated.
return {
on = {
timer = { 'every 6 hours' }
},

logging = {
level = domoticz.LOG_FORCE,
marker = '[WAN IP]'
},

execute = function(dz, devNil)
local dzb = dz.LOG_FORCE
local getIp = 'curl -s https://4.ifcfg.me/'
local tmpFile = 'C:\Program Files (x86)\Domoticz\temp/wanip.txt'
local actIp = ''
local devIp = dz.devices('Wan IP')
local currIp = devIp.text

os.execute(getIp..' > '..tmpFile)
actIp = io.open(tmpFile):read()

if actIp == nil then actIp = 'Unable to retrieve IP' end

if actIp ~= currIp then
msgTxt = 'Wan IP Changed: '..currIp..' ==> '..actIp
dz.log(msgTxt, dzb)
dz.notify('Wan IP', msgTxt, dz.PRIORITY_EMERGENCY)
devIp.updateText(actIp)dzb
os.execute('rm '..tmpFile)
else
dz.log('No variations', dzb)
end
end
}
dnacid
Posts: 2
Joined: Thursday 08 October 2015 11:10
Target OS: Windows
Domoticz version:
Contact:

Re: WanIP Checker

Post by dnacid »

Change:
local tmpFile = 'C:\Program Files (x86)\Domoticz\temp/wanip.txt'
to:
local tmpFile = 'C:\\Program Files (x86)\\Domoticz\\temp\\wanip.txt'

I Write my file to a directory without spaces so if the above doesnt work try that.
local tmpFile = 'C:\\Beheer\\Domoticz_Scripts\\wanip.txt'
User avatar
emme
Posts: 909
Joined: Monday 27 June 2016 11:02
Target OS: Raspberry Pi / ODroid
Domoticz version: latest
Location: Milano, Italy
Contact:

Re: WanIP Checker

Post by emme »

rlschulz wrote: Sunday 28 January 2018 21:38 and a little less Italian. :-)
oops! :oops: :oops: :oops:

:roll: :lol:
The most dangerous phrase in any language is:
"We always done this way"
EddyG
Posts: 1042
Joined: Monday 02 November 2015 5:54
Target OS: -
Domoticz version:

Re: WanIP Checker

Post by EddyG »

I agree with Egregius, beter use a bashscript.
This bashscript will do the job

Code: Select all

#!/bin/bash

fileip='/tmp/WANIP.txt'
filemsg='/tmp/WANIP.msg'
touch $fileip
touch $filemsg
ip=`wget -q -O - http://ipinfo.io/ip`
previp=`cat $fileip`
recipient='[email protected]'
echo $ip > $fileip
if [ "$ip" != "$previp" ]
 then
   echo "Provider changed your ipaddress from: $previp to: $ip" > $filemsg
   mailx -s "IP Change" $recipient < $filemsg
fi
rickiewickie
Posts: 6
Joined: Sunday 28 January 2018 12:51
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: WanIP Checker

Post by rickiewickie »

Hi all,

There are of course multiple ways to check your WAN IP, but this is my version.
Perhaps anyone is able to use it..

Code: Select all

-- Check WAN IP Script

-- Dummy devices to create
---		Ipaddress as text

--- Run script as time

commandArray = {}


local device_idx        = 446           -- IDX of the dummy device  
local logging 		    = 1				-- when true(1) will print output to log   
local sendnotification  = 1             -- send notification when your IP address is changed
              

--- DO NOT CHANGE ANYTHING BELOW ---
local time = os.date("*t")

function error(msg)
    print("--------------------------------------------------------------------------------------")
	print('-- IP Checker [ERROR] ==>  ' .. msg)
	print("--------------------------------------------------------------------------------------")
 end   
	
function message(msg)
    print("--------------------------------------------------------------------------------------")
    print('-- IP Checker ==>  ' .. msg)
	print("--------------------------------------------------------------------------------------")
end 


function getdevname4idx(deviceIDX)
	for i, v in pairs(otherdevices_idx) do
		if v == deviceIDX then
			return i
		end
	end
	return 0
end


function validate()

result = true
--
-- Switches and Devices Error logging.
--
       if not otherdevices[getdevname4idx(device_idx)] then
          error('Device [' .. getdevname4idx(device_idx) .. '] doesnt exist.')
             result = false   
       end
 
return result   
end


--- Start

time = os.date("*t")
if validate() and time.min % 15 == 0 then 

   local f = assert(io.popen("curl -s http://www.mijnip.nl/" , 'r'))
   local s = assert(f:read('*a'))

   ip = s:match([[<div id="remoteIPDiv">(.-)</div>]])
   ip = string.gsub(ip, "\n", "") -- remove line breaks
   
   
-- Update device if IP is changed
if otherdevices[getdevname4idx(device_idx)] ~= ip then
    commandArray['UpdateDevice'] = device_idx .. '|0|' .. tostring(ip) 
    message("IP Address changed to ".. otherdevices_svalues[device_name] )
        -- send notification in case your ip is changed.
        if sendnotification >= 1 then
        error("Notification has been sent.")
	    commandArray['SendNotification']='The WAN ip address is changed to '..ip 
	    end
end


if logging >= 1 then
print('Uw externe IP adres is  ==>  '.. ip)
end

end



return commandArray


Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest