Script reads public IP address from ADSL router using UnP

I know of three ways to get the present IP address of an ADLS router:

  • send a request to one of the “whatismyaddress” sites
  • write a script to log into your router and get the address from a status page
  • send a UPnP request to the router

The public IP address is an important thing to know if the router connects using dynamic IP. I use the following script to check my public IP now and then (every ten minutes actually) to detect changes, using UPnP. Another script then signals a dynamic IP name server about this.

UPnP is a protocol  for getting information from devices. UPnP-enabled routers can give you, amongst other information, your present public IP address. A program to query a router is miniupnpc, a program many Linux distributions provide.

upnpc -s

will retrieve a long string, one line in that string is

ExternalIPAddress =

So, here we go

import subprocess

def ipfromrouter():    
     p= subprocess.Popen(["/usr/bin/upnpc", "-s"], stdout=subprocess.PIPE)

     output= p.communicate()
     err= output[1]
     ip= output[0].split("\n")
     for i in ip:
           if i.find("ExternalIPAddress") >= 0:
                addr= i.split("=")[1]
                return addr.strip()  
     return None

if __name__ == "__main__":
        ip=  ipfromrouter()
        if ip:
                print "IP: ", ip

0 Responses to “Script reads public IP address from ADSL router using UnP”

Comments are currently closed.