Reputation: 175
I am trying to get LAN connected server's host names, so I can run query over these servers with hostname:
import socket
IP_RANGE = 10
hostNamesList = []
socket.setdefaulttimeout(0.1)
for i in range(IP_RANGE):
try:
hostNamesList.append(socket.gethostbyaddr("192.168.1.%s" % i)[0])
except:
pass
print hostNamesList
The above code takes several minutes to scan selected IP range, even if I set the timeout to 0.1 seconds.
Is there anything that I did wrong, or any way(s) to get host names faster?
Upvotes: 1
Views: 562
Reputation: 175
i have solved my problem thanks to yan's suggestion.It takes about 10 seconds instead of several minutes
import socket
from threading import Thread
hostNamesList=[]
def searchForSingleIP(i):
try:
hostNamesList.append(socket.gethostbyaddr("192.168.1.%s" % str(i) )[0])
except:
pass
for i in range(256):
worker = Thread(target = searchForSingleIP, args = (i,))
worker.start()
worker.join(timeout=0.05)
print hostNamesList
Upvotes: 2
Reputation: 305
You are probably running into long DNS or SAMBA lookup (just a guess). It's more of a network related behaviour, not python. Try running Your script with profiler: python -m cProfile -s tottime lookup.py
If my guess is correct You'd see a long _socket.gethostbyaddr
timing, then the only good option is to try paralleling Your code (or improving network settings for better lookup time).
Upvotes: 0