89 lines
2.4 KiB
Python
89 lines
2.4 KiB
Python
|
|
import sys
|
||
|
|
import socket
|
||
|
|
import os
|
||
|
|
from http.server import SimpleHTTPRequestHandler
|
||
|
|
from socketserver import TCPServer
|
||
|
|
from rich.console import Console
|
||
|
|
from rich.panel import Panel
|
||
|
|
from rich.text import Text
|
||
|
|
import json
|
||
|
|
from datetime import datetime
|
||
|
|
import hashlib
|
||
|
|
import urllib.request
|
||
|
|
import re
|
||
|
|
|
||
|
|
console = Console()
|
||
|
|
|
||
|
|
def get_machine_ip():
|
||
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||
|
|
try:
|
||
|
|
# doesn't have to be reachable
|
||
|
|
s.connect(('8.8.8.8', 80))
|
||
|
|
ip = s.getsockname()[0]
|
||
|
|
except Exception:
|
||
|
|
ip = '127.0.0.1'
|
||
|
|
finally:
|
||
|
|
s.close()
|
||
|
|
return ip
|
||
|
|
|
||
|
|
def is_docker():
|
||
|
|
# Check for .dockerenv file
|
||
|
|
if os.path.exists('/.dockerenv'):
|
||
|
|
return True
|
||
|
|
# Check cgroup info for docker
|
||
|
|
try:
|
||
|
|
with open('/proc/1/cgroup', 'rt') as f:
|
||
|
|
return 'docker' in f.read() or 'kubepods' in f.read()
|
||
|
|
except Exception:
|
||
|
|
return False
|
||
|
|
|
||
|
|
def get_host_ip():
|
||
|
|
try:
|
||
|
|
# Try resolving Docker internal host (works on Docker Desktop and configured Linux setups)
|
||
|
|
host_ip = socket.gethostbyname('host.docker.internal')
|
||
|
|
return host_ip
|
||
|
|
except socket.error:
|
||
|
|
# Fallback if not resolved, may use default gateway IP (requires extra code) or local IP
|
||
|
|
return 'Could not determine host IP'
|
||
|
|
|
||
|
|
def get_ipv4():
|
||
|
|
if is_docker():
|
||
|
|
ip = get_host_ip()
|
||
|
|
if ip:
|
||
|
|
print(f"Running inside Docker. Host IPv4: {ip}")
|
||
|
|
else:
|
||
|
|
print("Running inside Docker, but could not resolve host.docker.internal.")
|
||
|
|
else:
|
||
|
|
ip = get_machine_ip()
|
||
|
|
print(f"Not in Docker. Machine IPv4: {ip}")
|
||
|
|
return ip
|
||
|
|
|
||
|
|
PORT = 52721
|
||
|
|
IP = get_ipv4()
|
||
|
|
|
||
|
|
if len(sys.argv) > 1:
|
||
|
|
try:
|
||
|
|
PORT = int(sys.argv[1])
|
||
|
|
except ValueError:
|
||
|
|
console.print("[bold red]Usage:[/] python serve.py [port]", style="red")
|
||
|
|
sys.exit(1)
|
||
|
|
|
||
|
|
console.print(Panel(Text("Simple Python HTTP Server", style="bold white on blue"),
|
||
|
|
subtitle="Press [bold yellow]Ctrl+C[/] to stop the server", expand=False))
|
||
|
|
|
||
|
|
console.print(
|
||
|
|
f"[green]Server is running![/]\n"
|
||
|
|
f"Listening on [bold magenta]http://{IP}:{PORT}[/]\n",
|
||
|
|
style="bold",
|
||
|
|
)
|
||
|
|
|
||
|
|
try:
|
||
|
|
with TCPServer(("0.0.0.0", PORT), SimpleHTTPRequestHandler) as httpd:
|
||
|
|
httpd.serve_forever()
|
||
|
|
except KeyboardInterrupt:
|
||
|
|
console.print("\n[bold red]Server stopped by user.[/]")
|
||
|
|
except OSError as e:
|
||
|
|
console.print(f"[bold red]Error:[/] {e}")
|
||
|
|
|
||
|
|
|