Question

In: Computer Science

In this homework, you will practice and reinforce the basics of socket programming for TCP connections...

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

Solutions

Expert Solution

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()


Related Solutions

Coding Project 2: UDP Pinger In this lab, you will learn the basics of socket programming...
Coding Project 2: UDP Pinger In this lab, you will learn the basics of socket programming for UDP in Python. You will learn how to send and receive datagram packets using UDP sockets and also, how to set a proper socket timeout. Throughout the lab, you will gain familiarity with a Ping application and its usefulness in computing statistics such as packet loss rate. You will first study a simple Internet ping server written in the Python, and implement a...
Implement the following socket programming in C (b) Chat Application using TCP
Implement the following socket programming in C (b) Chat Application using TCP
Write a Java program that establishes a TCP connection with a mail server through the socket...
Write a Java program that establishes a TCP connection with a mail server through the socket interface, and sends an email message. Your program sends SMTP commands to local mail server, receives and processes SMTP commands from local mail server. It sends email message to one recipient at a time. The email message contains a typical message header and a message body. Here is a skeleton of the code you'll need to write: import java.io.*; import java.net.*; public class EmailSender...
Research the number of programming environments that support a socket interface.
Research the number of programming environments that support a socket interface.
write a skeleton Python TCP servers as follows: Multi-threaded concurrent TCP server using Python’s low-level socket...
write a skeleton Python TCP servers as follows: Multi-threaded concurrent TCP server using Python’s low-level socket module and Python’s threading library Python sockets API: s = socket(), s.bind(), s.listen(), remote_socket, remote_addr = s.accept() Python threading API: thread = threading.Thread(target, args, daemon), thread.start()
1. Consider running real-time traffic, like VoIP, over a TCP or UDP socket. Why might you...
1. Consider running real-time traffic, like VoIP, over a TCP or UDP socket. Why might you prefer to run such an application using a UDP transport layer? 2. Consider running real-time traffic, like VoIP, over a TCP or UDP socket. Suppose you chose to use TCP for your application; what would you need to do to ensure that the robust transport algorithm does not harm real-time performance?
For each of below python socket functions, describe network traffic (resulting TCP packets) that is generated...
For each of below python socket functions, describe network traffic (resulting TCP packets) that is generated at the TCP level. Note: s represents an open socket. Python network APIs Resulting TCP packets s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 8080)) s.send('ABC'.encode('utf-8')) data = s.recv(2000) s.shutdown(socket.SHUT_WR)
This problem will give you hands-on practice with the following programming concepts: • All programming structures...
This problem will give you hands-on practice with the following programming concepts: • All programming structures (Sequential, Decision, and Repetition) • Methods • Random Number Generation (RNG) Create a Java program that teaches people how to multiply single-digit numbers. Your program will generate two random single-digit numbers and wrap them into a multiplication question. The program will provide random feedback messages. The random questions keep generated until the user exits the program by typing (-1). For this problem, multiple methods...
This project will require you to demonstrate proficiency in programming using TCP/IP sockets by writing both...
This project will require you to demonstrate proficiency in programming using TCP/IP sockets by writing both a client program and a server program to provide Roman numeral to Arabic number translation. The client program must accept the –s servername flag and parameter to specify the hostname of the system running the server process, as well as accept the –p port-number flag and parameter indicating the port on which the server is listening. One (and only one) of the –r or...
I am new to socket programming and I wish to know what these lines of code...
I am new to socket programming and I wish to know what these lines of code do. I know they are creating UDP sockets, but it would help if someone explained what the code means. Thank you. Python Code: import socket testingSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) testingSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, testingSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) testingSocket.bind(('0.0.0.0', 50000)) send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) send_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) receiving_thread = Thread(target=self.receivingFunction) send_thread = Thread(target=self.sendMessage) broadcast_online_status_thread = Thread(target=onlineStatus)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT