Lab 10: Python Port Probing Project

Comp 150, Dordal, Mon, Apr 10, 2006 (swapped from Fri Apr 7)

The socket library

To include the socket library, use
      from socket import *
To create a socket, use
      s=socket()
Sockets are used to connect to a server. Use a new socket for each connection; they aren't meant for reuse (and don't work that way).

To connect to an address (see the next paragraph), use
      s.connect(address)
or
      s.connect_ex(address)
If a connection fails (eg because the server isn't listening at the specified address), the latter returns a numeric value != 0 while the former throws an exception which is harder to deal with within a loop or some larger program. To check the numeric value, use n=s.connect_ex(address) and then check n.

Addresses are pairs (hostname,port). The hostname is a string, and the ports we're interested in are in the range 2001-2030. The use of () to create a python pair object is likely new to you: you simply type ("ulam.math.luc.edu", 2001). The catch is that these parentheses are part of the pair, and you need a second set of parentheses for the connect call:
      n=s.connect_ex(("ulam.math.luc.edu",2001))

To read 1024 bytes of data from a connection (none of the servers we'll be accessing has more data than that), use
      s.recv(1024)
You need to print this; use the following:
      str = s.recv(1024)
      print str
It's probably a good idea to print a header too, like
      print "Port", portnum

Your assignment

Your assignment is to connect to every port in the range 2001-2030 on host "ulam.math.luc.edu", and read the data there. For a couple of those ports, the connection will fail, so you'll have to use s.connect_ex and skip if it returns a value!=0. To hit every port in the range 2001-2030, use a for loop:
for portnum in range(2001,2031):
    addr=("ulam.math.luc.edu", portnum)
    ...
Email me your python file, or show it to me.