import socket
import time

dns={}
def ip2name(ip):
    if dns.get(ip, None) and time.time() - dns[ip][1] < 600:
        return dns[ip][0]
    try:
       ret = timeout(socket.gethostbyaddr, args=[ip], default=(ip,), timeout_duration=1)[0]
    except herror:
        ret = ip
    dns[ip]=(ret, time.time())
    return ret

def timeout(func, args=(), kwargs={}, timeout_duration=10, default=None):
    """This function will spawn a thread and run the given function
    using the args, kwargs and return the given default value if the
    timeout_duration is exceeded.
    """ 
    import threading
    class InterruptableThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.result = default
        def run(self):
            try:
                self.result = func(*args, **kwargs)
            except:
                self.result = default
    it = InterruptableThread()
    it.start()
    it.join(timeout_duration)
    if it.isAlive():
        
        return it.result
    else:
        return it.result
