#!/usr/bin/env python3 ''' tcp_demo.py Jeff Ondich, 14 September 2016 A simple-minded example of how to open a TCP connection to a known web server and request a file there. Read the comments below to help you think about the many, many ways this program is not ready for production use. ''' import socket # Host and port to which we want to connect. Port 80 is # the conventional (but not universal) port for web servers. host = 'cs.carleton.edu' port = 80 # The underlying socket system, written in C, requires the # caller of sockte.rcv to specify both a buffer into which to read # data and the length of that buffer so the data won't overflow # the buffer. Even though Python reads the data using automatically # resizing buffer objects (typically type str), the C interface # bleeds into Python here, and requires that we specify a maximum # size for each rcv operation. block_size = 1000 # Pieces of the HTTP query get_line = 'GET /faculty/jondich/index.html HTTP/1.1\r\n' user_agent_line = 'User-Agent: Jeff\'s TCP Demo\r\n' host_line = 'Host: ' + host + '\r\n' http_query = get_line + user_agent_line + host_line + '\r\n' # Make the TCP connection and, just for fun, print out the name # of the server. sock = socket.create_connection((host, port)) print('Peer name: ', sock.getpeername()) print() # Make the HTTP query and print the retrieved data. Call rcv on the # socket repeatedly until you get either an empty string or a None back. # # Note that in Python 3, the sendall method expects a parameter of type "bytes" # (not a "str"), and rcv returns an object of type "bytes" as well. So in # this example, where we know ahead of time that the data will be UTF8-encoded # strings, we use encode and decode to move between bytes and str objects. sock.sendall(http_query.encode('utf-8')) data = sock.recv(block_size) while data: print(data.decode('utf-8')) data = sock.recv(block_size) sock.close() # See any security errors here? # Hint #1: what evil things could the server do? # Hint #2: what assumptions are we making about the data we get back?