Till
Till

Reputation: 29

Fast hostname/IP check in Python?

I have a list of hostnames and I want to check if these machines are running or not in an interval of about one second.

What I have until now is this, but the timeout on the machines which are offline take some seconds:

socket.setdefaulttimeout(0)
def resolve_hostname(hostname):
    try:
        return socket.gethostbyname(hostname)
    except socket.error:
        return False

Not good as the list has about 30 machines.

Any ideas how to speed things up a bit?

Thank you!

Upvotes: 3

Views: 1632

Answers (2)

kai
kai

Reputation: 2175

I don't have a connection with a slow name lookup to try, but the timeout seems to be respected exactly for socket.socket.connect()

import socket

def test_hostname(hostname, port, timeout=1.0):
    s = socket.socket()
    s.settimeout(timeout)
    try:
        s.connect((hostname, port))
    except (socket.timeout, socket.gaierror):
        return False
    else:
        return True
    finally:
        s.close()

Upvotes: 0

NPE
NPE

Reputation: 500167

Instead of coding this up yourself, I would look into using a third-party mass DNS resolver. Here is one that looks promising:

https://pypi.python.org/pypi/berserker_resolver/1.0.3

To install:

pip install berserker_resolver

Here is an example:

>>> import berserker_resolver
>>> resolver = berserker_resolver.Resolver()
>>> to_resolve = ['www.google.com', 'www.microsoft.com', 'www.facebook.com', 'invalid.invalid']
>>> resolver.resolve(to_resolve).keys()
['www.microsoft.com', 'www.facebook.com', 'www.google.com']

Upvotes: 2

Related Questions