Comp 150-001, MWF 12:35, Crown 105

Week 11

Homework 9: Network Communications

Your assignment is to create a TCP connection to, for ports 2000-2100 inclusive. You should connect, and then attempt to read data. There are three possible outcomes:

  1. The connection attempt failed
  2. The connection succeeded, but there was no data (that is, a timeout occurred)
  3. The connection succeeded and you got the data

Your program will mostly look like, below, in that you will be connecting to the server. However, you will be reading data from the server, not writing to it.

To look up, use the try/except from Create the addr pair, and the socket. You'll be doing this for each addr in range(2000, 2100).

    s = socket()

Then connect:


Case 1 above occurs if this connection attempt fails; that is, if res has a non-zero value.

Then set the timeout. 1.1 seconds is good. Again, see

Finally, recv some data. Here you model

    mesg = s.recv(2048)
except timeout:
    print("case 2 for port {}: connect but no data".format(portnum) )
    continue        # you *probably* do not need this

If there is data read, you need to print it. Print the port number also. To print mesg, you need to make it into a string:

    str(mesg, 'utf-8')

I've now included some 🐍 emojis (that was supposed to be a Python), so 'utf-8' is better than 'ascii'.

BUT: the str(mesg, ...) above won't work if mesg didn't get read because the server didn't return anything. In this case mesg is undefined, and trying to convert it to a str is an error. So here's a fix:

mesg = None        # now mesg is always defined; None is a special Python value
try: # same as before
if mesg != None: print(str(mesg, ...))    # only try to print if something was actually received

A problem with unicode

Sometimes str(mesg,'utf-8') fails because something is not understanding how to convert the plain bytes in mesg into unicode characters. Fixes:

1. Skip those ports:

    if port in [2037, 2058, 2071]: continue

2. Run python from the command line (bash/Terminal/cmd). The problem: this is probably a major pain on Windows

3. Use try/except on the bytes-to-string conversion

    response = str(buf,'utf-8')
    print('port {}: unicode conversion error'.format(port))
print('port {}: received string {}'.format(port, response)) 

Network fundamentals

  1. IP addresses
  2. TCP
  3. ports


except ...



Protocol issue: which end supplies the newline?