Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Ping in java

843790Apr 10 2007 — edited Sep 20 2007
Hi,

I am trying to ping a host through java,
here are the 3 ways am trying to achieve, first one works fine, but i do not want to use it.

1)
String ip = "127.0.0.1";
Process p = Runtime.getRuntime().exec("ping " + ip);
int status = p.waitFor();
System.out.println(ip + " is " + (status==0 ? "alive" : "dead"));

2)
InetAddress address = InetAddress.getByName("somemachine.somenetwork.com");

if(address != null ){ System.out.println("address created"); System.out.println("isreachable == " + address.isReachable(timeout));
} else
System.out.println("unreachable");

This kind of behaves weird or I have got my understanding wrong,
I think isReachable() uses ICMP echo/request to simulate ping,
but this does not work for me, isReachable() returns true for some cases and false for some, I have tried increasing the timeout too,
it doesnt even work for my localhost, not sure whats wrong, any ideas??

Also the hosts for which it returns false gets recognised via ping on the command prompt and the first case(obviously)

3)
Socket t = new Socket("127.0.0.1", 7);
BufferedReader br = new BufferedReader (new InputStreamReader(t.getInputStream()));
PrintStream ps = new PrintStream(t.getOutputStream());
ps.println("Hello");
String str = br.readLine();
if (str.equals("Hello"))
System.out.println("Alive!") ;
else
System.out.println("Dead or echo port not responding");
t.close();

here am trying to create a socket on the host on port 7(echo port)
This gives me the foll exception with any host:

java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)

Is there anything obviously wrong am doing here??

Please give me more info!

thanks!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 18 2007
Added on Apr 10 2007
26 comments
1,500 views