Ethan Hill
Ethan Hill

Reputation: 488

Python Simple Socket - Get URL from Client Request

For a school assignment, I am required to fill in the blanks of a sample Python 3 application that acts as a simple proxy server. I am required to only use the socket library.

My question lies in the fact that I was not taught how to pull the url of a request from a client, nor can I find information online to help me. Here's the code thus far (I'm including them to give an example of the style of Python I'll need to have written):

from socket import socket, gethostname, AF_INET, SOCK_STREAM
import sys

if len(sys.argv) <= 1:
    print ("Usage : 'python ProxyServer.py server_ip'\nserver_ip : It is the IP Address Of Proxy Server")
    sys.exit(2)

# Create a server socket, bind it to a port and start listening 
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(('localhost', 8888))
tcpSerSock.listen(5)

while 1: 

    # Start receiving data from the client 
    print ('Ready to serve...' )

    tcpCliSock, addr = tcpSerSock.accept()
    print ('Received a connection from:', addr)

    message = addr

    print (message.value)

    # Extract the filename from the given message     
    filename = message.split()[1].partition("/")[2] 
    print (filename)

When I go to queue the page, I navigate to 'localhost: 8080/www.google.com/'.

My question is, how in Python would I be able to read in 'www.google.com' as a string from the queued URL?

Upvotes: 2

Views: 5426

Answers (1)

Ethan Hill
Ethan Hill

Reputation: 488

This was the answer I found.

tcpCliSock.recv(4096)

^ The above returns a bytes object that contains the full request. When converted to a string and split based on spaces, the 'www.google.com' segment of the request is at position [1].

Off the top of my head, retrieving the URL would look like this:

test = message.split()[1]

Upvotes: 6

Related Questions