Skip to content

Instantly share code, notes, and snippets.

@amaork
Last active December 1, 2017 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amaork/d7bda4073598c2f1024e8aea015eed60 to your computer and use it in GitHub Desktop.
Save amaork/d7bda4073598c2f1024e8aea015eed60 to your computer and use it in GitHub Desktop.
Thread pool fast scan lan specify port host
import time
import socket
import websocket
import concurrent.futures
def get_host_address():
try:
for addr in socket.gethostbyname_ex(socket.gethostname())[2]:
if not addr.startswith("127."):
return addr
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 53))
return s.getsockname()[0]
except socket.error:
return socket.gethostbyname(socket.gethostname())
def connect_device(address, port=1234, timeout=0.01):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
s.connect((address, port))
s.close()
return address
except (socket.timeout, ConnectionError, ConnectionRefusedError, ConnectionResetError):
return None
start = time.time()
network_seg = ".".join(get_host_address().split(".")[:-1])
all_host = ["{}.{}".format(network_seg, i) for i in range(255)]
with concurrent.futures.ThreadPoolExecutor() as pool:
valid_host = filter(lambda x: x is not None, pool.map(connect_device, all_host))
print("{}".format(time.time() - start))
print(list(valid_host))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment