Lab 8: Python Port Probing Project

Comp 150, Dordal

You are to use the Python socket library to attempt connection to a range of ports on my server ulam2.cs.luc.edu, and if the connection succeeds to read what data you can from the port.

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).

Connection addresses are pairs (hostname, port), where the hostname is a string and the port is a number. To connect, 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.

Python uses the parentheses around an address to create a python pair object (or, more generally, a tuple): you simply type ("ulam2.cs.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(("ulam2.cs.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 "ulam2.cs.luc.edu", and read the data there. For some of those ports, the connection will fail, so you'll have to use s.connect_ex and skip if it returns a value!=0. If the connection fails, print the port and a message indicating the failure; if the connection succeeds, print the port and the data that you read. To hit every port in the range 2001-2030, use a for loop:
for portnum in range(2001,2031):
addr=("ulam2.cs.luc.edu", portnum)
...
Here's what my first few output lines looked like:
port  2001  ok: "hello"
port  2002  ok: "deuce"
port  2003  ok: "how is your program working today?"
port  2004  ok: "goodbye"
connect to port  2005  failed
connect to port  2006  failed

Email me your python file.