Using TCP/IP

?

=?ISO-8859-1?Q?Nagy_L=E1szl=F3_Zsolt?=

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,())
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,166
Messages
2,570,902
Members
47,443
Latest member
RobertHaddy

Latest Threads

Top