I'm working through a book called Python For Everbody and have been stuck on a problem for a couple of days. I'm pretty sure it's something super-simple I'm not seeing but just can't seem to crack it.
Apologies in advance if this is posted in the wrong place or not formatted correctly. This is my first post and am getting my head around it all.
So, the exercise is to start with a basic internet browser...
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) < 1:
break
print(data.decode(),end='')
mysock.close()
The task is to rewrite the code so it takes a url as an input. The problem I'm having is adding the input variable into the cmd line. I've tried the below:
import socket
# Establish url and server from user input
url = input('Please enter url>>')
clnpos = url.find(':')
server = url[clnpos +3:len(url)]
# Run program with variable
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((server), 80)
cmd = ('GET', (url), 'HTTP/1.0\r\n\r\n'.encode())
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) < 1:
break
print(data.decode(),end='')
mysock.close()
I've also tried making the cmd line a variable of its own...
import socket
url = input('Please enter url>>')
clnpos = url.find(':')
server = url[clnpos +3:len(url)]
cmdline = ('GET', (url), 'HTTP/1.0\r\n\r\n'.encode())
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((server), 80)
cmd = (cmdline)
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) < 1:
break
print(data.decode(),end='')
mysock.close()
Like I say, I'm pretty sure there's something silly I'm missing, almost feel embarrassed posting but I just can't see where I'm going wrong.
Any help offered would be very gratefully recieved.