Last active
December 12, 2015 04:18
-
-
Save DivinityArcane/4713128 to your computer and use it in GitHub Desktop.
Whoops.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' Simple Python HTTPD (Webpage Server) | |
- Justin Eittreim <eittreim.justin@live.com> | |
- http://DivinityArcane.deviantart.com/ | |
- :) ''' | |
import sys | |
pyver = float(sys.version[:3]) | |
from socket import socket, AF_INET, SOCK_STREAM | |
from time import strftime | |
class httpd: | |
def __init__(self, host, port): | |
self.host = host | |
self.port = port | |
self.sock = socket(AF_INET, SOCK_STREAM) | |
self.ipep = (host, port) | |
self.pages = { | |
'/': self.index, | |
'/favicon.ico': self.blank, | |
'/robots.txt': self.blank} | |
def listen(self): | |
self.sock.bind(self.ipep) | |
self.sock.listen(1) | |
self.can_run = True | |
while self.can_run: | |
(client, remote_endpoint) = self.sock.accept() | |
(remote_addr, remote_port) = remote_endpoint | |
payload = client.recv(1024) | |
payload = payload.decode('UTF-8') if pyver >= 3.0 else payload | |
if not payload or not '\r\n' in payload: | |
self.header(client, 403, 'Forbidden') | |
continue | |
data = payload.split('\r\n') | |
if len(data) < 1 or not ' ' in data[0]: | |
self.header(client, 403, 'Forbidden') | |
continue | |
head = data[0].split(' ') | |
if len(head) != 3 or head[0].upper() != 'GET': | |
self.header(client, 403, 'Forbidden') | |
continue | |
if head[1] in self.pages: | |
self.echo('{0} requested page: {1}'.format(remote_addr, head[1])) | |
self.pages[head[1]](client) | |
else: | |
self.header(client, 403, 'Forbidden') | |
client.close() | |
def send(self, client, content): | |
client.sendall(bytes(content, 'UTF-8') if pyver >= 3.0 else content) | |
def header(self, client, code, err): | |
self.send(client, 'HTTP/1.1 {0} {1}\r\nContent-Type: text/plain\r\n\r\n'.format(code, err)) | |
def response(self, client, body): | |
self.send(client, 'HTTP/1.1 200 OK\r\nContent-Length: {0}\r\nContent-Type: text/html\r\n\r\n{1}\r\n'.format(len(body), body)) | |
def index(self, client): | |
html = ''' | |
<html> | |
<head> | |
<title>Hello!</title> | |
</head> | |
<body> | |
<b>Hello, from <span style="color:#FF0000">Python {0}</span>!</b> | |
</body> | |
</html> | |
'''.format(sys.version) | |
self.response(client, html) | |
def blank(self, client): | |
self.header(client, 200, 'OK') | |
def echo(self, msg): | |
sys.stdout.write('[{0}] {1}\n'.format(strftime('%H:%M:%S'), msg)) | |
server = httpd('0.0.0.0', 80) | |
server.listen() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment