Skip to content

Instantly share code, notes, and snippets.

@CyrusF
Created April 22, 2019 04:46
Show Gist options
  • Select an option

  • Save CyrusF/811fc97420a3ac7019351cece204dabe to your computer and use it in GitHub Desktop.

Select an option

Save CyrusF/811fc97420a3ac7019351cece204dabe to your computer and use it in GitHub Desktop.
PyServer: a quick python HTTP server
# coding: UTF-8
import socket
import sys
from time import *
import os
HOST = ''
PORT = 8000
fmtstring = '''%s
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PyServer</title>
</head>
<body>
<h1 align="center">Request Info</h1>
<hr>
<pre>
From %s:%d
Time %s
</pre>
<pre>
%s
</pre>
<hr>
<div align="center">
<p>by PyServer 0.0.1</p>
</div>
</body>
</html>
'''
socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socket_server.bind((HOST, PORT))
socket_server.listen(10)
pid = os.getpid()
print '[*] Socket started (PID=%d)' % pid
while 1:
conn, addr = socket_server.accept()
print '[+] Connected with ' + addr[0] + ':' + str(addr[1])
response = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n'
timestamp = strftime("%Y-%m-%d %H:%M:%S", localtime(time()))
data = conn.recv(4096)
method = data.split(' ')[0]
print "\t" + data.replace("\n", "\n\t")
conn.sendall(fmtstring % (response, addr[0], addr[1], timestamp, data.strip()))
conn.close()
socket_server.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment