Java InetAddress Check isServerAlive(InetAddress host, int port)

Here you can find the source of isServerAlive(InetAddress host, int port)

Description

Check whether a server is alive.

License

Apache License

Parameter

Parameter Description
host the server host
port the server port

Return

true if a server is alive, false if a server is not alive.

Declaration

public static boolean isServerAlive(InetAddress host, int port) 

Method Source Code


//package com.java2s;
/*//  w w  w.j a va 2  s . c  o m
 * Copyright [2013-2015] eBay Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class Main {
    /**
     * Client connection retry count
     */
    public static final int RETRY_COUNT = 3;

    /**
     * Check whether a server is alive.
     * 
     * @param host
     *            the server host
     * @param port
     *            the server port
     * @return true if a server is alive, false if a server is not alive.
     */
    public static boolean isServerAlive(InetAddress host, int port) {
        Socket socket = null;
        int i = 0;
        while (i < RETRY_COUNT) {
            try {
                socket = new Socket(host, port);
                break;
            } catch (IOException e) {
                i++;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    Thread.currentThread().interrupt();
                }
            } finally {
                try {
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException ignore) {
                }
            }
        }
        return i != RETRY_COUNT;
    }
}

Related

  1. isReachable(final InetAddress inetAddress, final int timeout)
  2. isReachable(InetAddress address, int port)
  3. isReachable(NetworkInterface iface, InetAddress address, int timeout)
  4. isReservedAddr(InetAddress inetAddr)
  5. isServerAlive(InetAddress host, int port)
  6. isSiteLocalAddress(InetAddress i)
  7. isTenDot(InetAddress adr)
  8. isThisMyIpAddress(InetAddress addr)
  9. isThisMyIpAddress(InetAddress addr)