Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions src/ipscanner_py3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
import socket
from datetime import datetime
import json
import os
from multi.scanner_thread import split_processing


def get_absolute_path(relative_path: str) -> str:
"""Resolve relative path (like '../config.json') to absolute path."""
base_dir = os.path.dirname(os.path.abspath(__file__))
normalized = os.path.normpath(relative_path)
return os.path.join(base_dir, normalized)


# ---------- Core scan function ----------
def scan(addr: str, port: int = 135, timeout: float = 1.0) -> bool:
"""Return True if given addr:port accepts a TCP connection."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((addr, port))
sock.close()
return result == 0
except Exception:
return False

# threading
def run1(ips: list, start: int, end: int) -> None:
"""Scan a subset of IPs (ips[start:end]) for live hosts."""
for ip in ips[start:end]:
if scan(ip):
print(f"{ip} is live")

# ---------- Main program ----------
if __name__ == "__main__":
# Input base IP (e.g. 192.168.1.1)
net1 = input("Enter the IP address: ").strip()
net2 = net1.split('.')
if len(net2) < 3:
print(" Please enter a valid IPv4 address (e.g. 192.168.1.1).")
raise SystemExit(1)

# Build prefix like "192.168.1."
net3 = f"{net2[0]}.{net2[1]}.{net2[2]}."

# Banner
print("-" * 60)
print(f"Please wait, scanning IP address.... {net3}XXX")
print("-" * 60)

td1 = datetime.now()

# Load configuration
try:
with open(get_absolute_path('../config.json'), 'r', encoding='utf-8') as config_file:
config = json.load(config_file)

range_low = int(config['ipRange']['low'])
range_high = int(config['ipRange']['high'])
CONST_NUM_THREADS = int(config['thread']['count'])

except FileNotFoundError:
print(" config.json file not found at", get_absolute_path('../config.json'))
raise
except (KeyError, ValueError, json.JSONDecodeError) as e:
print(" Error reading config.json:", e)
raise


ips = [f"{net3}{i}" for i in range(range_low, range_high + 1)]

# Start threaded scanning
split_processing(ips, CONST_NUM_THREADS, run1)

td2 = datetime.now()
total = td2 - td1
print("-" * 60)
print(" Scanning completed in", total)
print("-" * 60)