public static boolean isPortAvailable(final int port, int protocol, InetAddress addr) {
    if (protocol == SOCKET) {
      // Try to create a ServerSocket
      if (addr == null) {
        return testAllInterfaces(port);
      } else {
        return testOneInterface(addr, port);
      }
    } else if (protocol == MULTICAST) {
      MulticastSocket socket = null;
      try {
        socket = new MulticastSocket();
        InetAddress localHost = LocalHostUtil.getLocalHost();
        socket.setInterface(localHost);
        socket.setSoTimeout(Integer.getInteger("AvailablePort.timeout", 2000));
        socket.setReuseAddress(true);
        byte[] buffer = new byte[4];
        buffer[0] = (byte) 'p';
        buffer[1] = (byte) 'i';
        buffer[2] = (byte) 'n';
        buffer[3] = (byte) 'g';
        InetAddress mcid = addr == null ? InetAddress.getByName(DEFAULT_MCAST_ADDRESS) : addr;
        SocketAddress mcaddr = new InetSocketAddress(mcid, port);
        socket.joinGroup(mcid);
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length, mcaddr);
        socket.send(packet);
        try {
          socket.receive(packet);
          return false;
        } catch (SocketTimeoutException ste) {
          // System.out.println("socket read timed out");
          return true;
        } catch (Exception e) {
          e.printStackTrace();
          return false;
        }
      } catch (java.io.IOException ioe) {
        if (ioe.getMessage().equals("Network is unreachable")) {
          throw new RuntimeException(
              "Network is unreachable", ioe);
        }
        ioe.printStackTrace();
        return false;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      } finally {
        if (socket != null) {
          try {
            socket.close();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    } else {
      throw new IllegalArgumentException(String.format("Unknown protocol: %d", protocol));
    }
  }
Returns whether or not the given port on the local host is available (that is, unused).

@param port The port to check
@param protocol The protocol to check (either {@link #SOCKET} or {@link #MULTICAST}).
@param addr the bind address (or mcast address) to use
@throws IllegalArgumentException <code>protocol</code> is unknown
geode-membership/src/main/java/org/apache/geode/internal/membership/utils/AvailablePort.java