Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

java ping problem  RSS feed

 
Baijun Jiang
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Recently I wrote a java program to ping devices but got rediculous results. Therefore I did a simple test:

import java.io.IOException;
import java.net.*;

public class test {

/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
String ip="192.168.1.222";
boolean returned=reachable(ip);
System.out.println(returned);
returned=InetAddress.getByName(ip).isReachable(1000);
System.out.println(returned);
}
private static boolean reachable(String address){
boolean returned;
DatagramSocket aSocket = null;
byte [] m = address.getBytes();
try
{
aSocket = new DatagramSocket();

InetAddress aHost = InetAddress.getByName(address);


DatagramPacket request = new DatagramPacket(m, address.length());
aSocket.connect(aHost, 7);
// now call either send or receive to see if connected
aSocket.send(request);
// if you got here then probably the other side is alive
returned=true;
}
catch (Exception ex)
{
System.out.println(ex);
returned=false;
}
return returned;
}
}

1.The ip I used does not exist in the network.
However I got this result after I ran this test:

true
true

2.After that I disabled mynetwork connection and ran the test again, I got:

java.net.NoRouteToHostException: No route to host: Datagram send failed
false
true

Conclusion: no matter what the InetAddress.getByName(ip).isReachable(1000) method will return me true value. The socket way is also giving me wrong information.

Can anyone tell me why this happens?

ps. I am using JDK 5.0 Update 7.
 
Joe Ess
Bartender
Posts: 9425
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you ping that IP from the command line? I'm using JDK 1.5.0_6 and I get false returned from InetAddress.isReachable() if I can't ping an address.
As for DatagramSocket, it uses UDP, which does not guarantee delivery. Bad choice for trying to validate the existance of a machine. Your best bet is to try to access some service that the remote machine makes available, which is what InetAddress.isReachable() may be implemented to do.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!