Java tips



Java Port Scanner

Here is a nice program to scan your localhost to see if you have any unexpected open ports (the first 100, but you can easily change this).




import java.net.*; import java.io.*; public class TCPscan { public static void main(String [] args) { int from = args.length > 0 ? Integer.parseInt(args[0]) : 0; int to = args.length > 1 ? Integer.parseInt(args[1]) : 100; String host = args.length > 2 ? args[2] : "localhost"; try { InetAddress ipAd = InetAddress.getByName(host); for (int i = from; i <= to; i++) { try { Socket s = new Socket(ipAd, i); System.out.println("TCP server on port " + i + " of " + host); s.close(); } catch (IOException e) { // must not be a server on port i } } } catch (UnknownHostException e) { System.err.println(e); } } }

Don't forget the classpath

When you find the following error:

     Exception in thread "main" java.lang.NoClassDefFoundError:

Remember, the current directory is probably excluded from the places where the JVM is looking for files.

Just add the current directory to the "classpath" (abbreviated cp) in the following way :


     java -cp . [Name of class containing the main method]


©HANDS-OFF 2006-8