Python Lookup Hostname from Ip with 1 Second Timeout

Python lookup hostname from IP with 1 second timeout

>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

Get Hostname from IP Address

You've already got the Python code required

socket.gethostbyaddr(ip)

What you need is on the infrastructure side of things. To get an internal hostname, you need to query the internal DNS server for the network in question. Larger networks almost always have internal DNS services but some smaller network don't since they rely on other means (direct IP, NETBIOS, Bonjour, etc.) to find various resources.

TL:DR : You need to query the internal DNS services for the network in question

Python socket.settimeout() not working when connecting to a domain that is down

This happens because the timeout for a Python socket does not limit the amount of time spent on DNS lookup. Since you are using a domain name that needs to be resolved to an IP, your s.connect((hostname, port)) will first need to make a DNS query for hostname, and only then it will be able to create a connection using one of the IPs returned by the DNS server (if any).

The domain 001.com does not seem to resolve to any IP address, so it can take several seconds for your system to return failure. When this happens, Python will bail out and the connection will fail, but the timeout will already be long expired.

If you know the IP address of the host you want to reach, use that instead of the hostname. If not, you will have to use a DNS resolution library to also time out DNS resolution, like for example dnspython:

import socket
import dns.resolver

def test_hostname(hostname, port):
resolver = dns.resolver.Resolver()
resolver.timeout = resolver.lifetime = 1

try:
answer = resolver.resolve(hostname, 'A')
except dns.exception.Timeout:
return False

if not answer.rrset:
return False

addr = next(iter(answer.rrset)).to_text()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)

try:
s.connect((addr, port))
except (socket.timeout, socket.gaierror):
return False
else:
return True
finally:
s.close()


Related Topics



Leave a reply



Submit