Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if an IP is alive in java?

There are 5 devices in my network with different IP addresses. I wish to connect to these devices and get data from them over TCP/IP socket when they are available in my network. How can I check if they are available in java?

public void setUpConnection() {
    try {
        Socket client = new Socket(hostIp, hostPort);
        socketReader = client.getInputStream();
        socketWriter = new PrintWriter(client.getOutputStream());
    } catch (UnknownHostException e) {
        System.out.println("Error setting up socket connection: unknown host at " +   hostIp);
        System.out.println("host: " + hostIp + "port: " + hostPort);
    } catch (IOException e) {
        System.out.println("Error setting up socket connection: " + e);
        System.out.println("host: " + hostIp + "port:" + hostPort);
    }
}
like image 503
michdraft Avatar asked Nov 28 '11 13:11

michdraft


2 Answers

InetAddress.getByName(host).isReachable(timeOut);

Further reference here

like image 66
Gonzalo Garcia Lasurtegui Avatar answered Oct 18 '22 23:10

Gonzalo Garcia Lasurtegui


if you just want to check whether or not the host is up, you can use isReachable

like image 21
Chris Avatar answered Oct 18 '22 21:10

Chris