Java Utililty Methods Socket Port

List of utility methods to do Socket Port

Description

The list of methods to do Socket Port are organized into topic(s).

Method

intgetFreeSocketPort()
Return a free port number.
int port = 0;
try {
    ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();
    s.close();
    return port;
} catch (IOException e) {
return port;
StringgetHostPort(Socket s)
get Host Port
String h = s.getInetAddress().getHostAddress().toString();
int port = s.getPort();
return h + ":" + port;
intgetMyPortNumber(ServerSocket serverSocket)
get My Port Number
return serverSocket.getLocalPort();
intgetPort(ServerSocket server)
get Port
int port = server.getLocalPort();
try {
    server.close();
} catch (IOException e) {
    e.printStackTrace();
return port;
ServerSocketgetRandomPortServerSocket()
get Random Port Server Socket
for (int port = 900; port < Short.MAX_VALUE; port++) {
    try {
        return new ServerSocket(port);
    } catch (IOException e) {
        continue;
throw new IOException("No free port found.");
...
ServerSocketgetServerSocket(int i_Port)
get Server Socket
ServerSocket v_Ret = null;
try {
    v_Ret = new ServerSocket(i_Port);
} catch (Exception exce) {
    v_Ret = null;
return v_Ret;
booleanisValidSocket(String host, int port)
is Valid Socket
try {
    Socket s = new Socket(host, port);
    boolean connected = s.isConnected();
    try {
        s.close();
    } catch (Exception e) {
    return connected;
...
voidreleasePort(ServerSocket ss)
release Port
if (ss == null)
    return;
try {
    ss.close();
} catch (IOException e) {
    e.printStackTrace();
return;
...
voidremoveSocket(String host, int port)
remove Socket
try {
    Socket socket = sockets.get(host + ":" + port);
    if (socket != null) {
        socket.close();
        sockets.remove(host + ":" + port);
} catch (IOException e) {
    e.printStackTrace();
...
voidwaitForSocket(int port)
wait For Socket
long notAfter = System.currentTimeMillis() + 5000;
for (; System.currentTimeMillis() < notAfter;) {
    Socket sock = null;
    try {
        Thread.sleep(100);
        sock = new Socket("127.0.0.1", port);
        break;
    } catch (Exception ex) {
...