import socket
import os
from datetime import datetime

# ------------------------------------------------------------
# PATHS
# ------------------------------------------------------------
OUTPUT_HTML = r"c:\Temp\projectServer\HTML\openPorts.html"
os.makedirs(os.path.dirname(OUTPUT_HTML), exist_ok=True)

# ------------------------------------------------------------
# TCP PORT SCAN FUNCTION
# ------------------------------------------------------------
def scan_port(port):
    """Return True if TCP port is open on 127.0.0.1."""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.settimeout(0.1)  # fast timeout
        result = s.connect_ex(("127.0.0.1", port))
        return result == 0

# ------------------------------------------------------------
# SCAN ALL 65,535 PORTS
# ------------------------------------------------------------
open_ports = []

print("🔍 Scanning 127.0.0.1 for open TCP ports (1–65535)...")

for port in range(1, 65536):
    if scan_port(port):
        print(f"OPEN: {port}")
        open_ports.append(port)

print("\n✅ Scan complete.")
print(f"Total open ports: {len(open_ports)}")

# ------------------------------------------------------------
# BUILD HTML REPORT
# ------------------------------------------------------------
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

html = f"""
<!DOCTYPE html>
<html>
<head>
<title>Open Ports Report</title>
<style>
    body {{
        font-family: Arial, sans-serif;
        background: #1e1e1e;
        color: #e0e0e0;
        padding: 20px;
    }}
    h1 {{
        color: #4fc3f7;
    }}
    table {{
        width: 300px;
        border-collapse: collapse;
        margin-top: 20px;
    }}
    th {{
        background: #333;
        padding: 10px;
        border-bottom: 2px solid #555;
    }}
    td {{
        padding: 8px;
        border-bottom: 1px solid #444;
        text-align: center;
    }}
    tr:hover {{
        background: #2a2a2a;
    }}
</style>
</head>
<body>

<h1>Open TCP Ports on 127.0.0.1</h1>
<p>Scan completed: {timestamp}</p>
<p>Total open ports: {len(open_ports)}</p>

<table>
<tr><th>Port</th></tr>
"""

for port in open_ports:
    html += f"<tr><td>{port}</td></tr>"

html += """
</table>
</body>
</html>
"""

# ------------------------------------------------------------
# WRITE HTML FILE
# ------------------------------------------------------------
with open(OUTPUT_HTML, "w", encoding="utf-8") as f:
    f.write(html)

print(f"\n📄 HTML report saved to: {OUTPUT_HTML}")
