Skip to content

Instantly share code, notes, and snippets.

@heiswayi
Created March 7, 2024 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heiswayi/5b746d792f806440f0570285eb7ab805 to your computer and use it in GitHub Desktop.
Save heiswayi/5b746d792f806440f0570285eb7ab805 to your computer and use it in GitHub Desktop.
Simple HTTP File Server - Convenient script to transfer file within LAN
import http.server
import socket
import sys
def check_port_in_use(port):
# Check if the specified port is in use
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('localhost', port)) == 0
def find_available_port(start_port):
# Find an available port starting from the specified port
port = start_port
while check_port_in_use(port):
port += 1
return port
def start_file_server(port):
# Start the HTTP file server on the specified port
handler = http.server.SimpleHTTPRequestHandler
with http.server.HTTPServer(('localhost', port), handler) as server:
print(f"Server started on http://localhost:{port}/")
server.serve_forever()
if __name__ == "__main__":
default_port = 8000
# Check if a port is provided as a command-line argument
if len(sys.argv) > 1:
try:
custom_port = int(sys.argv[1])
if 0 < custom_port < 65535:
port = custom_port
else:
print("Invalid port number. Using the default port:", default_port)
except ValueError:
print("Invalid port. Using the default port:", default_port)
else:
port = default_port
# Check if the chosen port is in use and find an available one if necessary
if check_port_in_use(port):
print(f"Port {port} is in use. Finding an available port...")
port = find_available_port(port)
print(f"Found available port: {port}")
# Start the file server on the chosen/available port
start_file_server(port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment