Using TCP/IP

Nagy László Zsolt nagylzs at freemail.hu
Wed Oct 8 07:11:11 EDT 2003


>
>
>>I get the same error here.  But this works:
>>
>>    
>>
>>>>>socket.gethostbyname_ex(socket.gethostname())
>>>>>          
>>>>>
>>('noodle.noodle.org', ['noodle'], ['127.0.0.1'])
>>
>>    
>>
>        Unfortunately, the original poster was looking for a way to get the IP 
>number of their (dynamic?) network connection. The above doesn't do 
>that.
>
>        192.168.0.1 is my 10/100 interface, but 99.9% of the time, that is not 
>active. My dial-up IP can not be readily obtained.
>
>  
>
Try this module:


"""
Get IP address towards external addresses.

This module provides the L{getmyip} function that will return the 
external ip address of the current machine.
Loading this module requires an active internet connection and it may be 
slow (depending on connection speed).
Internal IP cache will be refreshed in every L{UPDATE_INTERVAL} second 
in a separate thread so you may get a
false address for a while if you change your external IP address in 
runtime."""

import socket
import thread
import threading
import time

"""@var UPDATE_INTERVAL: Determine how often the internal IP cache will 
be updated."""
UPDATE_INTERVAL = 5
"""
@var COMMON_HOST: A common host. It is required to establish an active 
connection and get client
addres from the created socket. You can change this to a site near you 
so you can connect to it
in a jiffy."""
COMMON_HOST = 'www.google.com'
"""@var COMMON_PORT: port to connect to. See L{COMMON_HOST}."""
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():
"""
@return: The external ip address of the current machine towards external 
addresses.
"""
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,())
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20031008/73334d95/attachment.html>


More information about the Python-list mailing list