How do I check if an IP is alive in java?
15,063
Solution 1
InetAddress.getByName(host).isReachable(timeOut);
Further reference here
Solution 2
if you just want to check whether or not the host is up, you can use isReachable
Solution 3
For pure Java there are basically two methods:
Active: as your example, but looping thru all ports and all bound IP's on the host
Passive: running a small server on predefined port(s) and the other one will register themself when they get available.
isReachable may fail for a lot of reasons as stated in the docs.
Comments
-
michdraft almost 2 years
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); } }
-
michdraft over 12 yearsThese are all my device's host and port: 1- 192.168.30.190:3001 2- 192.168.30.191:3001 3- 192.168.30.192:3001 4- 192.168.30.193:3001 5- 192.168.30.194:3001 Could you please give a sample of Passive way?
-
michdraft over 12 yearsIs this good? Can i relay on it? public boolean hostAvailabilityCheck(){ boolean available = true; try { (new Socket(host, port)).close(); } catch (UnknownHostException e) { // unknown host available = false; } catch (IOException e) { // io exception, service probably not running available = false; } return available; }
-
PeterMmm over 12 yearsIf your devices config is a fix set, then write some thread that tries to connect with timeout to each of them as your example. For all other setups (host/ip/port detection) IMHO you need a DHCP server because pure Java don´t reach the network layers to do this in a clean way.