Last active
December 1, 2017 03:57
-
-
Save amaork/d7bda4073598c2f1024e8aea015eed60 to your computer and use it in GitHub Desktop.
Thread pool fast scan lan specify port host
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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