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

Week 11



Homework 9: Network Communications

Your assignment is to create a TCP connection to ulam.cs.luc.edu, 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 stalkc.py, 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 ulam.cs.luc.edu, use the try/except from stalkc.py. Create the addr pair, and the socket. You'll be doing this for each addr in range(2000, 2100).

    addr=(dest,portnum)
    s = socket()

Then connect:

    res=s.connect_ex(addr)

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 stalkc.py.

Finally, recv some data. Here you model stalks.py:

try:
    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

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


Network fundamentals

  1. IP addresses
  2. TCP
  3. ports

Exceptions:

try:
    thing()
except ...
    do_if_didnt_work()

stalks.py, stalkc.py

server:

client:

Protocol issue: which end supplies the newline?