#!/usr/bin/env python2

# httpEcho.py -- program to parrot back http headers sent by a browser

from socket import *
from string import join
import sys

PORT = 2080  # default port

RESPONSE = \
"""HTTP/1.1 200 OK
Connection: Close
Content_type: text/html

<html>
<head><title>HTTP Echo Response</title>
</head>
<body>
<pre>
%s
</pre>
</body>
</html>"""

def start_server(port):
    s = socket(AF_INET,SOCK_STREAM)
    s.bind((gethostname(),port))
    s.listen(1)
    print "Echo server listening on %s" % port
    while 1:
        sock,addr = s.accept()
        print "\nconnection from", addr
        inFile = sock.makefile()

        # Read lines until end of headers found
        lines = []
        while 1:
            line = inFile.readline()
            if line == "\r\n": break  # exit loop at blank line
            lines.append(line)
        inFile.close()

        print "Got request, sending response"
        sock.sendall(RESPONSE % join(lines,""))
        sock.close()
        print "Response sent"

if __name__ == '__main__':
    if len(sys.argv) > 1:
        start_server(int(sys.argv[1]))
    else:
        start_server(PORT)
