Message32522
Hi,
I wrote a small function to translate an IP to a hostname (eg. 212.27.33.225 => "linuxfr.org").
---------------------------------------------
from socket import gethostbyaddr, herror as socket_host_error
def ip2name(addr):
try:
if addr in ip2name.cache:
return ip2name.cache[addr]
name = gethostbyaddr(addr)[0]
except (socket_host_error, KeyboardInterrupt, ValueError):
name = addr
ip2name.cache[addr] = name
return name
ip2name.cache = {}
---------------------------------------------
Problem: sometimes gethostbyaddr() takes 5 seconds to answer "unknown host" so I hit CTRL+c to interrupt hit. But the "try/except" block doesn't catch the interruption. I found a workaround: use double try/except (try: gethostbyaddr() except KeyboardInterrupt: raise).
Last version of my function
---------------------------------------------
def ip2name(addr):
if not ip2name.resolve:
return addr
try:
if addr in ip2name.cache:
return ip2name.cache[addr]
# FIXME: Workaround Python bug
# Need double try/except to catch the bug
try:
name = gethostbyaddr(addr)[0]
except KeyboardInterrupt:
raise
except (socket_host_error, ValueError):
name = addr
except (socket_host_error, KeyboardInterrupt, ValueError):
ip2name.resolve = False
name = addr
ip2name.cache[addr] = name
return name
ip2name.cache = {}
ip2name.resolve = True
---------------------------------------------
I'm using Python 2.5.1 on Ubuntu Feisty (Linux kernel 2.6.20).
To reproduce my error, try "10.0.0.1" or "192.168.0.1" (or any other IP). |
|
Date |
User |
Action |
Args |
2007-08-23 14:58:41 | admin | link | issue1755388 messages |
2007-08-23 14:58:41 | admin | create | |
|