In: Computer Science
In this homework, you will practice and reinforce the basics of socket programming for TCP connections in Python: how to create a socket, bind it to a specific address and port, as well as send and receive a HTTP packet. You will also learn some basics of HTTP header format. The requirements for this homework are specified below.
1. Function Requirement: You will develop a web server that handles one HTTP request at a time. Your web server should accept and parse the HTTP request, get the requested file from the server’s file system, create an HTTP response message consisting of the requested file preceded by header lines, and then send the response directly to the client. If the requested file is not present in the server, the server should return an HTTP 404 “Not Found” msg.
2. Security Requirement: Note that this Web server will allow its clients to access ANY file that they can name. To prevent strangers from snooping on your files, you should include some basic protections: 1. If the request goes to “/grades/students.html”, your server should return an HTTP 403 “Forbidden” response. 2. Additionally, to prevent directory listing, the same 403 message needs to be returned if the request goes to “/grades/” folder.
Skeleton Code
Below you will find the skeleton code for the Web server. You are to complete the skeleton code. The places where you need to fill in code are marked with #Fill in. Each place may require one or more lines of code.
Running the Server
Put an HTML file (e.g., HelloWorld.html) in the same directory that the server is in. Run the server program. Determine the IP address of the host that is running the server (e.g., 128.238.251.26, or 127.0.0.1 if you run your server program locally on your own device). In either case, you can open up a browser on your client machine and type the following URL.
http://127.0.0.1:6789/HelloWorld.html
where 6789 is the port number you hardwired into your server code and ‘HelloWorld.html’ is the name of the file you placed in the server directory (case matters!). The browser should then display the contents of HelloWorld.html. Don’t forget the port number; if you leave it out the browser will use the default HTTP port 80 and you won’t get a result. Then try to get a file that is not present at the server. You should get a 404 “Not Found” message. For security feature testing, you can create a folder named ‘grades’ inside your server directory and test it in your browser by replacing ‘HelloWorld.html’ with ‘grades/students.html’ or ‘grades/’.
Skeleton Python Code for the Web Server
#import socket module
from socket import *
import sys # In order to terminate the program
serverSocket = socket(AF_INET , SOCK_STREAM)
# Prepare a server socket on a particular port # Fill in code to
set up the port
while True:
# Establish the connection
print(’Ready to serve...’)
connectionSocket, addr = # Fill in code to get a connection
try:
message = # Fill in code to read GET request filename =
message.split()[1]
# Fill in security code
f = open(filename)
outputdata = # Fill in code to read data from the file # Send
HTTP header line(s) into socket
# Fill in code to send header(s)
# Send the content of the requested file to the client for i in
range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode()) connectionSocket.send("\r\n".encode()) connectionSocket.close()
except IOError:
# Send response message for file not found # Fill in
# Close client socket
# Fill in
serverSocket.close()
sys.exit() # Terminate the program after sending the corresponding
data
If you have any doubts, please give me comment...
#Import socket module
from socket import *
import socket # Alternative (better) syntax
# Create a TCP server socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_STREAM is used for TCP)
# serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Alternative (better) syntax
# Assign a port number
serverPort = 6788
# Bind the socket to server address and server port
serverSocket.bind(("", serverPort))
# or
# serverSocket.bind((gethostname(), serverPort))
# serverSocket.bind((socket.gethostname(), serverPort)) # Alternative (better) syntax
# Listen to at most 1 connection at a time
serverSocket.listen(1)
# Server should be up and running and listening to the incoming connections
while True:
print 'Ready to serve...'
# Set up a new connection from the client
connectionSocket, addr = serverSocket.accept()
# If an exception occurs during the execution of try clause
# the rest of the clause is skipped
# If the exception type matches the word after except
# the except clause is executed
try:
# Receives the request message from the client
message = connectionSocket.recv(1024)
print 'Message is: ', message
# Extract the path of the requested object from the message
# The path is the second part of HTTP header, identified by [1]
filename = message.split()[1]
print 'File name is: ', filename
# Because the extracted path of the HTTP request includes
# a character '/', we read the path from the second character
f = open(filename[1:])
# Store the entire contenet of the requested file in a temporary buffer
outputdata = f.read()
# Send the HTTP response header line to the connection socket
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")
# Send the content of the requested file to the connection socket
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.send("\r\n")
# Close the client connection socket
connectionSocket.close()
except IOError:
# Send HTTP response message for file not found
connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n")
connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n")
# Close the client connection socket
connectionSocket.close()
serverSocket.close()