Java InetAddress Check isReachable(InetAddress address, int port)

Here you can find the source of isReachable(InetAddress address, int port)

Description

is Reachable

License

Open Source License

Declaration

public static boolean isReachable(InetAddress address, int port) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static boolean isReachable(InetAddress address, int port) {
        return isReachable(address, Arrays.asList(port));
    }//from  ww  w  .ja  v  a 2s .c o m

    public static boolean isReachable(InetAddress address,
            List<Integer> ports) {
        if (isReachableByEcho(address)) {
            return true;
        }

        boolean reachable = false;
        for (Integer port : ports) {
            reachable = reachable || isPortOpen(address, port);
        }

        return reachable;
    }

    private static boolean isReachableByEcho(InetAddress address) {
        try {
            return address.isReachable(300);
        } catch (IOException e) {
            return false;
        }
    }

    private static boolean isPortOpen(InetAddress address, int port) {
        Socket socket = null;
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(address, port), 1000);
            return true;
        } catch (IOException e) {
            return false;
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // noop
                }
            }
        }
    }
}

Related

  1. isPublic(InetAddress inetAddress)
  2. isPublicIp(InetAddress addr)
  3. isPublicIP4Address(InetAddress localAddress)
  4. isPubliclyRoutable(final InetAddress addrIP)
  5. isReachable(final InetAddress inetAddress, final int timeout)
  6. isReachable(NetworkInterface iface, InetAddress address, int timeout)
  7. isReservedAddr(InetAddress inetAddr)
  8. isServerAlive(InetAddress host, int port)
  9. isServerAlive(InetAddress host, int port)