How can I tell if a port is used without attempting to connect to it?
I don't think you can. You can, though, use a try block around the attempt to connect, and then have a catch block that catches the exception, if one is thrown. The problem you are seeing is that the exception is thrown, but nothing catches it.