[ python-Bugs-1755388 ] Problem with socket.gethostbyaddr() and KeyboardInterrupt

SourceForge.net noreply at sourceforge.net
Tue Jul 17 12:07:41 CEST 2007


Bugs item #1755388, was opened at 2007-07-17 12:07
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1755388&group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Extension Modules
Group: Python 2.5
Status: Open
Resolution: None
Priority: 5
Private: No
Submitted By: STINNER Victor (haypo)
Assigned to: Nobody/Anonymous (nobody)
Summary: Problem with socket.gethostbyaddr() and KeyboardInterrupt

Initial Comment:
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).

----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1755388&group_id=5470


More information about the Python-bugs-list mailing list