LocalPortScanner

You can attempt to determine which ports are currently occupied by trying to create server sockets on all of them, and seeing where that operation fails.

import java.net.*;
import java.io.IOException;


public class LocalPortScanner {

  public static void main(String[] args) {

    // first test to see whether or not we can bind to ports
    // below 1024
    boolean rootaccess = false;
    for (int port = 1; port < 1024; port += 50) {
      try {
        ServerSocket ss = new ServerSocket(port);
        // if successful
        rootaccess = true;
        ss.close();
        break;
      }
      catch (IOException ex) {
      }
    }
    
    int startport = 1;
    if (!rootaccess) startport = 1024;
    int stopport = 65535;
    
    for (int port = startport; port <= stopport; port++) {
      try {
        ServerSocket ss = new ServerSocket(port);
        ss.close();
      }
      catch (IOException ex) {
        System.out.println("Port " + port + " is occupied.");
      }
    
    }

  }

}

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified December 15, 1999