Ping in java
843790Apr 10 2007 — edited Sep 20 2007Hi,
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!