This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author vstinner
Recipients
Date 2007-07-17.10:07:41
SpamBayes Score
Marked as misclassified
Message-id
In-reply-to
Content
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).
History
Date User Action Args
2007-08-23 14:58:41adminlinkissue1755388 messages
2007-08-23 14:58:41admincreate