How to test if a remote system is reachable - java

I want to test whether a remote system is reachable using Java or in other words "send a ping" using Java. This functionality should be encapsulated in a method with boolean value, for example
public boolean isReachable(String ip) {
// what to do :-)
}
I've tested the Java Process class, but I don't think that it is the best way to do this, because of the complex output handling with OutputBuffers.
Process proc = Runtime.getRuntime().exec("ping " + ip);
Another possibility would be creating a Socket Connection and handle thrown exceptions, but if the remote system is a "naked" unix system, there might be no Socket on the other side :-) Additionally, I'd like to be able to set a timeout, when a remote system is not reachable.
So how could I do this? Thank you!

InetAddress.getByName(ip).isReachable(timeout);

InetAddress.getByName(host).isReachable(timeOut) (seen here)

It looks like you are using Linux so you will probably find that isReachable() is unreliable (because you will not have permissions to send ICMP packets, and very few servers have the Echo service running).
If that is the case then I think you will need to use spawn a Process in the way you suggest, but I recommend using a command like:
ping -c 1 hostname
This will terminate after one attempt and you can then examine the exit status of the process - much more reliable than parsing standard output.
Ping returns 0 for success non-zero on failure.

I think isReachable() can't be used as reliable option. Better pure java option I think will be something like this:
private static boolean isReachable(String host, int openPort, int timeOutMillis) {
try {
try (Socket soc = new Socket()) {
soc.connect(new InetSocketAddress(host, openPort), timeOutMillis);
}
return true;
} catch (IOException ex) {
return false;
}
}
And if you want to check if host is accessible via web/browser here is it:
private static boolean hostsWebApp(String host, int timeOutMillis) {
boolean isReachable = isReachable(host, 80, timeOutMillis);
if(!isReachable) {
return isReachable(host, 443, timeOutMillis);
} else {
return true;
}
}

I know this question has found its answer but I'd like to add my code just for "copy-paste".
public boolean isIpReachable(String ip, int timeout){
boolean state = false;
try {
state = InetAddress.getByName(ip).isReachable(timeout);
} catch (IOException e) {
//Parse error here
}
return state;
}

Related

Selenium to check log files

Does anyone know if it is possible to use selenium WebDriver (im using java) to check for messages in log files?
Currently the only way to know if an action in the front end of our system has completed is to ssh into our servers and wait for confirmation from the log files. This is how the process is tested manually but now I need to automate that test. Is it possible to use selenium to check this out?
My current method to achieve this seems overly complex:
Run actions in Front end
Launch shell Script to check log files from Selenium Test (includes ssh to server as logs are stored there)
Create "Action Completed" message in simple text file on server if logs show action is completed otherwise show "Action NOT completed"
scp file back to my machine/VM
read in file to eclipse
Create method in test to check contents of file something like if ("Action completed" message is returned -> continue) else (repeat from bullet point 2)
Is there a simpler way???
Self Answer - After considering all the posts, this is the solution I came up with that works really well. I have wirtten a method which allows me to parse the logs using regex right from Eclipse. Below is the code with heavy commenting to show what I have done....
public void checkLogs() throws IOException{
//create an empty string to hold the output
String s = null;
// using the process API and runtime exec method to directly ssh in the client machine and run any command you like. I need the live logs so I used tail -f
Process p = Runtime.getRuntime().exec("ssh user#ipaddress tail -f /location/file");
// use buffered reader to bring the output of the command run on the clinet machine back to the output in eclipse. I also created an output for the error stream to help with debugging if the commands dont work as I am not directly looking at the output when I run the commands on the client machine
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// For my test I only want to continue with the clicks in the front end once I know the system has been reset. For our system this can only be checked in the logs. So I created a boolean flag which will only become true once the regex I run matches lines from the output. Use a while loop with != null to check every line of the output
boolean requestArrived = false;
while ((s = stdInput.readLine()) != null) {
System.out.println(s); // so I can see live what is happening. (great for debugging)
//search for the specific string that lets me know the system has been started the reset. (can run any regex here)
if(r.equalsIgnoreCase("system reset request received")){
System.out.println("***********************************************************************************************");
// Change the state of the boolean flag to true as we know now that the backend is ready to continue
requestArrived = true;
}
if(t.equalsIgnoreCase("System reset has happened successfully"))// a secondary check to see when the system is ready to continue{
System.out.println("##############################################################################################");
//if both string that we are looking for have been received we can continue with the rest of the script
if (requestArrived) {
break;
}
}
}
//close the terminal
p.destroy();
}
I hope that helps someone :)
Add a special page to your site that tails the logfile. Have a shared secret that selenium knows and the site if you need to keep the logfile confidential. Then just visit that page and use the usual methods to check for strings
There may be some permissions problems to overcome: normally web applications shouldn't be able to see the logs.
With the present solution you describe, Selenium is not really the right tool for the job (even though you could probably find a solution).
I can see several possible approaches:
Add a page that shows the progress (as suggested by Vorsprung). This could be a separate page, or some message in the existing GUI. This could be only for Selenium, or maybe it could even become a proper feature for all users (or only for administrators), if it makes sense for your system.
Use a system like you describe, but run the server on the local system (as a special test instance). Then you can skip the SSHing.
Create some service (REST or similar) on the server to query job status. Again, this may be useful for more than just testing.
What makes sense depends on how the system is used (how users currently check whether a job has completed, what information about a job is interesting, etc.).
EDIT: I misread your question, As you were asking for a simpler solution, but I tried to provide solution for the complex approach. Anyways I hope it will be useful.
Actual Answer:
I had done following activity for my project
clear logs using a shell script on remote unix server
Perform front end activity
capture logs after predefined time (say, 60 seconds )
SFtp back to client machine
first you will need an SFTP client and SSH client to interact with unix server
here Node is an object containing Unix env details. so change accordingly.
Using JSch lib for this
public static String runCommand(String Command, Node node )
{
String output = null;
if (node.getConnType().equals("SSH")){
int exitStatus = 0;
try{
JSch jsch=new JSch();
JSch.setConfig("StrictHostKeyChecking", "no");
Session session=jsch.getSession(node.getUserName(), node.getHost(), 22);
session.setPassword(node.getPassword());
session.setConfig("PreferredAuthentications",
"publickey,keyboard-interactive,password");
session.connect();
String command=Command;
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
output = new String(tmp, 0, i);
}
if(channel.isClosed()){
if(in.available()>0) continue;
exitStatus= channel.getExitStatus();
//System.out.println("exit-status: "+exitStatus);
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
e.printStackTrace();
}
if (exitStatus == 0)
{
if(output != null)
return output.replaceAll("[\\n\\r]", "");
}
}
return null;
}
SFTP client
public boolean transferFileSFTP(Node node,String srcDir,String targetDir,String srcFileName,String targetFileName, String direction)
{
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession(node.getUserName(), node.getHost(), 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("PreferredAuthentications",
"publickey,keyboard-interactive,password");
session.setPassword(node.getPassword());
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
System.out.println("src:" + srcDir+srcFileName );
System.out.println("target:" + targetDir+targetFileName );
sftpChannel.get(targetDir+targetFileName, srcDir+srcFileName);
sftpChannel.exit();
session.disconnect();
return true;
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
return false;
}
Now,
To wait until desired time and make it thread based to collect logs simultaneously from different applications involved,
using ExecutorService and Future<String> utilities
So created one LogCollector class which will initiate request and another is ThreadClass(logical) which will perform activities on log file.
LogCollector.java
public class LogCollector {
private static ExecutorService pool = Executors.newFixedThreadPool(100);
private static List<Future<String>> list = new ArrayList<Future<String>>();
public static void add(Node node, String srcDir, String targetDir, String srcFileName, String targetFileName, long wait )
{
list.add(pool.submit(new LogCollectorThread(System.currentTimeMillis()/1000,wait, srcDir, targetDir, srcFileName, targetFileName, node )));
}
public static void getResult()
{
try{
for (Future<String> future : list) {
String out =future.get();
//DO whatever you want to do with a response string return from your thread class
}
pool.shutdown();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
LogCollectorThread.java
public class LogCollectorThread implements Callable<String>{
long startTime;
long wait;
String srcFileName;
String targetFileName;
String srcDir;
String targetDir;
Node node;
public LogCollectorThread(long startTime, long wait,String srcDir, String targetDir,String srcFileName, String targetFileName,
Node node) {
super();
this.startTime = startTime;
this.wait = wait;
this.srcFileName = srcFileName;
this.targetFileName = targetFileName;
this.srcDir = srcDir;
this.targetDir = targetDir;
this.node = node;
}
/***
* Returns a String with Parameters separated by ',' and status at the end
* status values:
* 0 - successfully retrieved log file
* 1 - failure while retrieving log file
*/
#Override
public String call() throws Exception {
while((System.currentTimeMillis()/1000 - startTime)<=wait)
{
Thread.sleep(1000);
}
MyFTPClient sftp= new MyFTPClient();
boolean result =sftp.transferFileSFTP(this.node, this.srcDir, this.targetDir, this.srcFileName, this.targetFileName, "From");
System.out.println(this.node.getHost() + ","+ this.srcDir + ","+this.targetDir +","+ this.srcFileName +","+ this.targetFileName);
if(result == true)
return this.node.getHost() + ","+ this.srcDir + ","+this.targetDir +","+ this.srcFileName +","+ this.targetFileName +"," + "0" ;
else
return this.node.getHost() + ","+ this.srcDir + ","+this.targetDir +","+ this.srcFileName +","+ this.targetFileName +"," + "1" ;
}
}
How to use LogCollector classes:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
Helper.runCommand("cd /opt/redknee/app/crm/current/log/; echo > AppCrm.log", testEnv.getBSS());
LogCollector.add(testEnv.getBSS(), "collectedLogs\\", "/opt/redknee/app/crm/current/log/", timeStamp + "_" + testEnv.getBSS().getHost() + "_BSS_AppCrm.log" , "AppCrm.log", 60);
//So your thread is working now, so now perform your Front End Activity
//After 60 seconds, log file will be SFTPed to client host
//You can perform you activity before adding logCollectorThread or just before that
LogCollector.getResult();
Here I have given too much code,
But it is too hard to describe each step line by line.
Main thing i wanted to prove is using java most of the things are possible.
It is upto you to decide how critical it is and is it worth doing.
Now coming to your exact requirement of searching for a particular string.
As you can see in logCollectorThread,
currently i am doing nothing but just waiting till 60 seconds to complete.
So here you can use runCommand to grep desired string from logs
you can use command like
grep -i "Action Completed" | grep -v 'grep' | wc -l
if it return 1, you found your string
Similarly you can check for failure message.
and return desired string from your thread and get it as result in threadCollector.getResult() method.
And Once file is FTPed to your client, parsing it for a particular string using Java would be very easy. StackOverflow will help you in that :)
declaimer: don't expect code to be fully working.
It will work but you have to put your efforts. your java knowledge will be needed to plug-in the missing pieces
To check the action got completed, checking server logs might be solution. But still in GUI, we could see visibility of some html elements or messages or java script variable or overriding javscript functions.
With the help of Selenium JavscriptExecutor, we can override alert method (refer example 21)similarly we can override onreadystatechange for the request/response completion.
JavaScript Window variables can be used to show the action completeness by checking after each ajax request.
We can use selenium wait to wait for an element to be visible, identify an element using xpath.
There are more tutorials available in the below link for element wait, typing in textbox and so on.
http://software-testing-tutorials-automation.blogspot.com/2014/05/selenium-webdriver-tutorials-part-two.html

Only works in debugging mode

I'm trying to create a program for a distributed system. At the moment I have a thread for listening to connections, and a thread for sending, and a thread for receiving.
I've reached a problem where the client will connect but only when using breakpoints. I can't figure out the problem at all!. I've tried to implement things to slow the program down however nothing is working.
If you guys could take a look i'd be greatly appreciative.
public static void main(String[] args)
{
System.out.println("Server starting on port 5000");
RecievingConnection reciever = new RecievingConnection(5000,0); //Recieving Connection
reciever.start();
SendingConnection sender = new SendingConnection(5001,1); //Sending Connection
sender.start();
while(true){
while(reciever.ready==true){
System.out.println("In");
nodes first = new nodes(reciever.socket,0);
System.out.println("Node created");
first.start();
System.out.println("Client connected on port: " + reciever.socket.getLocalAddress());
nodes second = new nodes(sender.socket,1);
second.start();
reciever.ready=false;
sender.ready=false;
reciever.connectionComplete=true;
sender.connectionComplete=true;
}
}
}
public RecievingConnection(int port, int mode)
{
Serverport = port;
connectionMode = mode;
try{
server = new ServerSocket(port);
server.setSoTimeout(100000);
}
catch(IOException ex)
{
System.out.println(ex);
}
}
public void run(){
while(true){
if(ready == false){
try {
socket = server.accept();
ready = true;
System.out.println("Attempting to connect using port: " + Serverport);
while(connectionComplete == false){
//wait
}
} catch (IOException ex) {
System.out.println(ex);
}
}
}
}
The sending thread is basically the same code. Any idea what the problem is? "Nodes" is the thread for each node.
I solved it by adding a sleep in the main thread. I presume this is because the main thread takes priority over child threads?
Your problem is almost certainly at:
while (connectionComplete == false) {
//wait
}
This will loop forever, the other thtreads will not get any cpu time at all. It also explains why it works in debug - it's because in debug if you stop at a breakpoint, any other threads will get time.
You should at least do:
while (connectionComplete == false) {
//wait
Thread.sleep(0);
}
and maybe use a number much greater than 0. This will allow other thtreads a chance to run.
I am not suggesting that this will make your code work correctly but it should remove the current problem.
After that there's another tight loop that won't let any other thread time.
while (true) {
if (ready == false) {
Change that to:
while (true) {
if (ready == false) {
// ...
} else {
// Here too.
Thread.sleep(0);
}
}
You can't just share variables between threads. Make them volatile, synchronize or use CAS types like AtomicBoolean.
Read about it.
https://docs.oracle.com/javase/tutorial/essential/concurrency/interfere.html
http://www.journaldev.com/1061/java-synchronization-and-thread-safety-tutorial-with-examples
https://docs.oracle.com/javase/tutorial/essential/concurrency/atomicvars.html
Besides class "nodes" is not described here and classes are expected to start with an upper case letter.

How can I figure out network connection is available in java? [duplicate]

This question already has answers here:
How to detect network breakage using java program?
(2 answers)
Closed 9 years ago.
How can I figure out network connection is available in java? I want to get information about network connection. If it is available, I'll connect to network for fetching data otherwise I use local database.
Is There any solution?
Try to connect the network, as you said. If fails, repeat e.g. 3 times. If still failling, use local database. You don't have to additionally ping anything.
For simplicity you can use Jodd HTTP library, for example:
try {
HttpRequest.get("http://stackoverflow.com").send();
return true;
} catch (Exception ex) {
return false;
}
Such as #igor said: "Try to connect the network, as you said. If fails, repeat e.g. 3 times. If still failling, use local database. You don't have to additionally ping anything."
For Example:
public class InternetConnection {
/* use at least one reliable host, in most cases you will want
to use the one you're working with later */
private static final String CHECK_URL = "http://www.t-online.de/";
public static InternetConnectionState isAvailable() {
try {
URL url = new URL(InternetConnection.CHECK_URL);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
Object objData = urlConnection.getContent();
} catch(UnknownHostException exception) {
return new InternetConnectionState(false);
} catch(IOException exception) {
return new InternetConnectionState(false);
}
return new InternetConnectionState(true);
}
}
Main link
You can ping the host.
See
java code to ping an IP address
If you want to check whether database is accessible or not you may catch the Connection Exceptions which can occur during the attempt to connect. Subsequently you can use local database if it fails
You can use java.net.NetworkInterface for that, here's a simple example no how to do it:
public boolean isConnectedToNetwork() {
Enumeration<NetworkInterface> interfaceEnumeration = NetworkInterface.getNetworkInterfaces();
while (interfaceEnumeration.hasMoreElements()) {
NetworkInterface each = interfaceEnumeration.nextElement();
if (!each.isLoopback() && each.isUp()) {
return true;
}
}
return false;
}
Notice that you have to check if it's not a loopback interface.

Reconnect Serial Port on Processing

I'm using processing and I'm reading inputs from Arduino with a serial port but connection drop may occur, in this case how to I reopen this connection?
You can catch RuntimeExceptions thrown by Serial.java, which generally indicate the serial port is no longer available. Within that catch block, then, you can start polling the serial port; once it allows you to reinstantiate your Serial instance, the port is again available (e.g. the USB cable is plugged back in) and you're back in the game.
Serial serial;
boolean serialInited;
void setup () {
initSerial();
}
void draw () {
if (serialInited) {
// serial is up and running
try {
byte b = serial.read();
// fun with serial here...
} catch (RuntimeException e) {
// serial port closed :(
serialInited = false;
}
} else {
// serial port is not available. bang on it until it is.
initSerial();
}
}
void initSerial () {
try {
serial = new Serial(this, Serial.list()[0], BAUD_RATE);
serialInited = true;
} catch (RuntimeException e) {
if (e.getMessage().contains("<init>")) {
System.out.println("port in use, trying again later...");
serialInited = false;
}
}
}
Rather than attempting to reconnect every frame, you might instead want to use a counter that limits the frequency of reconnection attempts. (e.g. count to 10, try again, repeat as needed.) Shouldn't matter that much, but dunno...banging that hard on the serial port may have unexpected side effects due to something I know little about.
In the Arduino IDE, you would have to close the Serial port monitor and then go back to [Tools] -> [Serial Port] to re-select your serial port.
This is because when you disconnect the cable, you are removing the serial device you were previously using. Linux handles this better than windows, but either way, it plays havoc with the serial monitor.
Instead of removing the USB cable, you should press the reset button on the board to restart your program.
Also, keep in mind that many Arduinos have an Auto-Reset on Serial communication "feature". I posted directions to a work-around here.

Why does InetAddress.isReachable return false, when I can ping the IP address?

InetAddress byName = InetAddress.getByName("173.39.161.140");
System.out.println(byName);
System.out.println(byName.isReachable(1000));
Why does isReachable return false? I can ping the IP.
The "isReachable" method has not been worthy of using for me in many cases. You can scroll to the bottom to see my alternative for simply testing if you're online and capable of resolving external hosts (i.e. google.com) ... Which generally seems to work on *NIX machines.
The issue
There is alot of chatter about this :
Here are other, similar questions :
Detect internet Connection using Java
How do I test the availability of the internet in Java?
And even a reported bug on this same matter :
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4921816
Part 1 : A reproducible example of the problem
Note that in this case, it fails.
//also, this fails for an invalid address, like "www.sjdosgoogle.com1234sd"
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
for (InetAddress address : addresses) {
if (address.isReachable(10000))
{
System.out.println("Connected "+ address);
}
else
{
System.out.println("Failed "+address);
}
}
//output:*Failed www.google.com/74.125.227.114*
Part 2 : A Hackish Workaround
As an alternative, you can do this :
// in case of Linux change the 'n' to 'c'
Process p1 = java.lang.Runtime.getRuntime().exec("ping -n 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
The -c option of ping will allow ping to simply try to reach the server once(as opposed to the infinite ping which we're used to using at the terminal).
This will return 0 if the host is reachable. Otherwise, you will get "2" as a return value.
Much simpler - but of course it is platform specific.
And there may be certain privilege caveats to using this command - but I find it works on my machines.
PLEASE Note that :
1) This solution is not production quality. Its a bit of a hack. If google is down, or your internet is temporarily slow, or maybe even if there is some funniness in your privileges/system settings, if could return false negatives (i.e. it could fail even though the input address is reachable).
2) The isReachable failure is an outstanding issue. Again - there are several online resources indicating that there is no "perfect" way of doing this at the time of this writing, due to the way the JVM tries to reach hosts - I guess it is an intrinsically platform specific task which, although simple, hasn't yet been abstracted sufficiently by the JVM.
I came here to get an answer for this same question, but I was unsatisfied by any of the answers because I was looking for a platform independent solution. Here is the code which I wrote and is platform independent, but requires information about any open port on the other machine (which we have most of the time).
private static boolean isReachable(String addr, int openPort, int timeOutMillis) {
// Any Open port on other machine
// openPort = 22 - ssh, 80 or 443 - webserver, 25 - mailserver etc.
try {
try (Socket soc = new Socket()) {
soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis);
}
return true;
} catch (IOException ex) {
return false;
}
}
Update: Based on a recent comment to this answer, here is a succinct version of the above code:
private static boolean isReachable(String addr, int openPort, int timeOutMillis) {
// Any Open port on other machine
// openPort = 22 - ssh, 80 or 443 - webserver, 25 - mailserver etc.
try (Socket soc = new Socket()) {
soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis);
return true;
} catch (IOException ex) {
return false;
}
}
If you only want to check if it is connected to internet use this method , It returns true if internet is connected, Its preferable if you use the address of the site you are trying to connect through the program.
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("http://www.google.com");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
Just mentioning it explicitly since the other answers don't. The ping part of isReachable() requires root access on Unix. And as pointed out by bestsss in 4779367:
And if you ask why ping from bash doesn't, actually it does need as well. Do that ls -l /bin/ping.
Since using root was not an option in my case the solution was to allow access to port 7 in the firewall to the specific server I was interested in.
I am not sure what was the state when the original question was asked back in 2012.
As it stands now, ping will be executed as a root. Through the ping executable's authorization you will see the +s flag, and the process belonging to root, meaning it will run as root. run ls -liat on where the ping is located and you should see it.
So, if you run InetAddress.getByName("www.google.com").isReacheable(5000) as root, it should return true.
you need proper authorizations for the raw socket, which is used by ICMP (the protocol used by ping)
InetAddress.getByName is as reliable as ping, but you need proper permissions on the process to have it running properly.
Since you can ping the computer, your Java process should run with sufficient privileges to perform the check. Probably due to use of ports in the lower range. If you run your java program with sudo/superuser, I'll bet it works.
I would suggest that the ONLY reliable way to test an internet connection is to actually connect AND download a file, OR to parse the output of an OS ping call via exec(). You cannot rely on the exit code for ping and isReachable() is crap.
You cannot rely on a ping exit code as it returns 0 if the ping command executes correctly. Unfortunately, ping executes correctly if it can't reach the target host but gets a "Destination host unreachable" from your home ADSL router. This is kind of a reply that gets treated as a successfull hit, thus exit code = 0. Have to add though that this is on a Windows system. Not checked *nixes.
private boolean isReachable(int nping, int wping, String ipping) throws Exception {
int nReceived = 0;
int nLost = 0;
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("ping -n " + nping + " -w " + wping + " " + ipping);
Scanner scanner = new Scanner(process.getInputStream());
process.waitFor();
ArrayList<String> strings = new ArrayList<>();
String data = "";
//
while (scanner.hasNextLine()) {
String string = scanner.nextLine();
data = data + string + "\n";
strings.add(string);
}
if (data.contains("IP address must be specified.")
|| (data.contains("Ping request could not find host " + ipping + ".")
|| data.contains("Please check the name and try again."))) {
throw new Exception(data);
} else if (nping > strings.size()) {
throw new Exception(data);
}
int index = 2;
for (int i = index; i < nping + index; i++) {
String string = strings.get(i);
if (string.contains("Destination host unreachable.")) {
nLost++;
} else if (string.contains("Request timed out.")) {
nLost++;
} else if (string.contains("bytes") && string.contains("time") && string.contains("TTL")) {
nReceived++;
} else {
}
}
return nReceived > 0;
}
nping is number of try to ping ip(packets), if you have busy network or systems choose biger nping numbers.
wping is time waiting for pong from ip, you can set it 2000ms
for using this method u can write this:
isReachable(5, 2000, "192.168.7.93");
Or using this way:
public static boolean exists(final String host)
{
try
{
InetAddress.getByName(host);
return true;
}
catch (final UnknownHostException exception)
{
exception.printStackTrace();
// Handler
}
return false;
}
InetAddress.isReachable is flappy, and sometimes returns unreachable for addresses which we can ping.
I tried the following:
ping -c 1 <fqdn> and check the exit status.
Works for all the cases i had tried where InetAddress.isReachable doesn't work.
To Check Internet
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
//You can replace it with your name
return !ipAddr.equals("");
} catch (Exception e1) {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("/system/bin/ping -W 1 -c 1 www.google.com");
int returnVal = 0;
returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e2) {
e2.printStackTrace();
return false;
}
}
}
To check network connectivity
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
Because isReachable is using the TCP protocol(by WireShark) The Ping command is using ICMP protocol,if you want to return true you need to open the 7 port

Categories