code: public static boolean isPortAvailable(int port) {
          StringBuilder builder = new StringBuilder();
          builder.append("Testing port ").append(port).append("\n");
          try (Socket s = new Socket("localhost", port)) {
              // If the code makes it this far without an exception it means
              // something is using the port and has responded.
              builder.append("Port ").append(port).append(" is not available").append("\n");
              return false;
          } catch (IOException e) {
              builder.append("Port ").append(port).append(" is available").append("\n");
              return true;
          } finally {
              log.fine(builder.toString());
          }
      }
docs: Checks if a port is available by opening a socket on it
  @param port the port to test
  @return true if the port is available