diff options
| author | gigagamerchaddhruv-spec <gigagamerchaddhruv@gmail.com> | 2026-05-02 20:57:41 +0530 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-05-02 20:57:41 +0530 |
| commit | 2e54a1525ba484df6be0dbcf176c4f09f07b491c (patch) | |
| tree | b7590114650eb978a95370c80b0e12288506bf25 /scanner.py | |
| parent | cc8bb2b4e2434f3a09243e7259d239b831d03eca (diff) | |
Refactor host checking and port scanning logic
Refactored host checking and port scanning functionality. Replaced is_host_alive with ping function to measure latency and removed common_ports dictionary.
Diffstat (limited to 'scanner.py')
| -rw-r--r-- | scanner.py | 67 |
1 files changed, 33 insertions, 34 deletions
@@ -1,57 +1,56 @@ -import socket +import platform +import subprocess import ipaddress -COMMON_PORTS = { - 22: "SSH", - 80: "HTTP", - 443: "HTTPS", - 445: "SMB" -} - NETWORK = "192.168.1.0/24" -def is_host_alive(ip): +def ping(ip): + system = platform.system().lower() + + if system == "windows": + cmd = ["ping", "-n", "1", "-w", "500", str(ip)] + else: + cmd = ["ping", "-c", "1", "-W", "1", str(ip)] + try: - socket.create_connection((str(ip), 80), timeout=0.2) - return True - except: - return False + output = subprocess.run( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True + ) + if output.returncode == 0: -def scan_ports(ip): - open_ports = [] + # very simple latency extraction + text = output.stdout - for port, name in COMMON_PORTS.items(): - try: - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.settimeout(0.2) + for line in text.splitlines(): + if "time=" in line: + return line.split("time=")[1].split(" ")[0] - if sock.connect_ex((str(ip), port)) == 0: - open_ports.append(f"{port}:{name}") + return "ok" - sock.close() - except: - pass + except: + pass - return open_ports + return None def scan_network(): - devices = {} + devices = [] net = ipaddress.ip_network(NETWORK, strict=False) for ip in net.hosts(): - ip_str = str(ip) - - if is_host_alive(ip): + latency = ping(ip) - devices[ip_str] = { - "ip": ip_str, - "ports": scan_ports(ip), - "status": "alive" - } + if latency: + devices.append({ + "ip": str(ip), + "latency": latency + }) return devices |
