Detect IP changes
Nagy László Zsolt
nagylzs at freemail.hu
Thu Mar 20 10:11:03 EST 2003
>Is there a reliable way to detect the change of a dynamic IP address ?
>If I use socket.gethostbyname('my_dynip_name') I still get the old IP, even
>thougt my system's DNS has been refreshed with the new name-address binding
>...
>A solution should be platform independent.
>
>Thanks for your answers!
>
>
It seems you are having the same problems I was having.. :-)
You can use this module below. You must have an active internet connection
to load it. Call the getmyip() function to get your ip address. On
multi-hosted machines,
it will return the IP address of your external (internet) connection.
Laci 1.0
#!/usr/bin/env python
"""Get IP address towards external addresses"""
import socket
import thread
import threading
import time
UPDATE_INTERVAL = 5 # Update cached ip in every 60 minutes.
COMMON_HOST = 'www.google.com'
COMMON_PORT = 80
_lock = threading.Lock()
_cached_ip = None
def _getmyip():
global _lock
global _cached_ip
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((COMMON_HOST,COMMON_PORT))
ip = s.getsockname()[0]
s.close()
_lock.acquire()
try:
_cached_ip = ip
finally:
_lock.release()
def getmyip():
global _lock
global _cached_ip
_lock.acquire()
try:
return _cached_ip
finally:
_lock.release()
def _update_cached_ip():
while 1:
time.sleep(UPDATE_INTERVAL)
_getmyip()
_getmyip()
thread.start_new_thread(_update_cached_ip,())
More information about the Python-list
mailing list