/* * @(#)Ping.java 1.2 01/12/13 * Connect to each of a list of hosts and measure the time required to complete * the connection. This example uses a selector and two additional threads in * order to demonstrate non-blocking connects and the multithreaded use of a * selector. * * Copyright 2001-2002 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * -Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduct the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that Software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */import java.io.*; import java.net.*; import java.nio.*; import java.nio.channels.*; import java.nio.charset.*; import java.util.*; import java.util.regex.*; public class Ping { // The default daytime port static int DAYTIME_PORT = 13; // The port we'll actually use static int port = DAYTIME_PORT; // Representation of a ping target // static class Target { InetSocketAddress address; SocketChannel channel; Exception failure; long connectStart; long connectFinish = 0; boolean shown = false; Target(String host) { try { address = new InetSocketAddress(InetAddress.getByName(host), port); } catch (IOException x) { failure = x; } } void show() { String result; if (connectFinish != 0) result = Long.toString(connectFinish - connectStart) + "ms"; else if (failure != null) result = failure.toString(); else result = "Timed out"; System.out.println(address + " : " + result); shown = true; } } // Thread for printing targets as they're heard from // static class Printer extends Thread { LinkedList pending = new LinkedList(); Printer() { setName("Printer"); setDaemon(true); } void add(Target t) { synchronized (pending) { pending.add(t); pending.notify(); } } public void run() { try { for (;;) { Target t = null; synchronized (pending) { while (pending.size() == 0) pending.wait(); t = (Target)pending.removeFirst(); } t.show(); } } catch (InterruptedException x) { return; } } } // Thread for connecting to all targets in parallel via a single selector // static class Connector extends Thread { Selector sel; Printer printer; // List of pending targets. We use this list because if we try to // register a channel with the selector while the connector thread is // blocked in the selector then we will block. // LinkedList pending = new LinkedList(); Connector(Printer pr) throws IOException { printer = pr; sel = Selector.open(); setName("Connector"); } // Initiate a connection sequence to the given target and add the // target to the pending-target list // void add(Target t) { SocketChannel sc = null; try { // Open the channel, set it to non-blocking, initiate connect sc = SocketChannel.open(); sc.configureBlocking(false); sc.connect(t.address); // Record the time we started t.channel = sc; t.connectStart = System.currentTimeMillis(); // Add the new channel to the pending list synchronized (pending) { pending.add(t); } // Nudge the selector so that it will process the pending list sel.wakeup(); } catch (IOException x) { if (sc != null) { try { sc.close(); } catch (IOException xx) { } } t.failure = x; printer.add(t); } } // Process any targets in the pending list // void processPendingTargets() throws IOException { synchronized (pending) { while (pending.size() > 0) { Target t = (Target)pending.removeFirst(); try { // Register the channel with the selector, indicating // interest in connection completion and attaching the // target object so that we can get the target back // after the key is added to the selector's // selected-key set t.channel.register(sel, SelectionKey.OP_CONNECT, t); } catch (IOException x) { // Something went wrong, so close the channel and // record the failure t.channel.close(); t.failure = x; printer.add(t); } } } }
private void ping(String ip) {
Runtime rt=Runtime.getRuntime();
int ret = -1;
try {
//rt = Runtime.getRuntime();
Process p = rt.exec("ping "+ip);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s;
while ((s = bufferedReader.readLine()) != null) {
//System.out.println(s);
if (s.indexOf("ttl=") > -1 || s.indexOf("TTL=") > -1) {
System.out.println("up");
break;
} else
System.out.println("down");
}
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
finally{
rt.gc();//强制回收
}
return ret;
}
It's not possible to really "ping" a machine to check if it's alive or not (it's a long story, but to keep it short I will just say that the Socket class is not low-level enough for that operation). But we can emulate a ping by talking the "echo port". On a server, the echo port is always port 7. We write a string to that port and the server will echo the string. import java.io.*;
import java.net.*;public class PseudoPing {
public static void main(String args[]) {
try {
Socket t = new Socket(args[0], 7);
DataInputStream dis = new DataInputStream(t.getInputStream());
PrintStream ps = new PrintStream(t.getOutputStream());
ps.println("Hello");
String str = is.readLine();
if (str.equals("Hello"))
System.out.println("Alive!") ;
else
System.out.println("Dead or echo port not responding");
t.close();
}
catch (IOException e) {
e.printStackTrace();}
}
}
NOTE: To make this a more "complete PING", you may want to check this How-to to display the response time.
--------------------------------------------------------------------------------
Written and compiled by Réal Gagnon ©1998-2000 mailto:[email protected]
* @(#)Ping.java 1.2 01/12/13
* Connect to each of a list of hosts and measure the time required to complete
* the connection. This example uses a selector and two additional threads in
* order to demonstrate non-blocking connects and the multithreaded use of a
* selector.
*
* Copyright 2001-2002 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY
* DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR
* RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR
* ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE
* FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT,
* SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF
* THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or
* intended for use in the design, construction, operation or
* maintenance of any nuclear facility.
*/import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
import java.util.regex.*;
public class Ping { // The default daytime port
static int DAYTIME_PORT = 13; // The port we'll actually use
static int port = DAYTIME_PORT;
// Representation of a ping target
//
static class Target { InetSocketAddress address;
SocketChannel channel;
Exception failure;
long connectStart;
long connectFinish = 0;
boolean shown = false; Target(String host) {
try {
address = new InetSocketAddress(InetAddress.getByName(host),
port);
} catch (IOException x) {
failure = x;
}
} void show() {
String result;
if (connectFinish != 0)
result = Long.toString(connectFinish - connectStart) + "ms";
else if (failure != null)
result = failure.toString();
else
result = "Timed out";
System.out.println(address + " : " + result);
shown = true;
} }
// Thread for printing targets as they're heard from
//
static class Printer
extends Thread
{
LinkedList pending = new LinkedList(); Printer() {
setName("Printer");
setDaemon(true);
} void add(Target t) {
synchronized (pending) {
pending.add(t);
pending.notify();
}
} public void run() {
try {
for (;;) {
Target t = null;
synchronized (pending) {
while (pending.size() == 0)
pending.wait();
t = (Target)pending.removeFirst();
}
t.show();
}
} catch (InterruptedException x) {
return;
}
} }
// Thread for connecting to all targets in parallel via a single selector
//
static class Connector
extends Thread
{
Selector sel;
Printer printer; // List of pending targets. We use this list because if we try to
// register a channel with the selector while the connector thread is
// blocked in the selector then we will block.
//
LinkedList pending = new LinkedList(); Connector(Printer pr) throws IOException {
printer = pr;
sel = Selector.open();
setName("Connector");
} // Initiate a connection sequence to the given target and add the
// target to the pending-target list
//
void add(Target t) {
SocketChannel sc = null;
try { // Open the channel, set it to non-blocking, initiate connect
sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(t.address); // Record the time we started
t.channel = sc;
t.connectStart = System.currentTimeMillis(); // Add the new channel to the pending list
synchronized (pending) {
pending.add(t);
} // Nudge the selector so that it will process the pending list
sel.wakeup(); } catch (IOException x) {
if (sc != null) {
try {
sc.close();
} catch (IOException xx) { }
}
t.failure = x;
printer.add(t);
}
} // Process any targets in the pending list
//
void processPendingTargets() throws IOException {
synchronized (pending) {
while (pending.size() > 0) {
Target t = (Target)pending.removeFirst();
try { // Register the channel with the selector, indicating
// interest in connection completion and attaching the
// target object so that we can get the target back
// after the key is added to the selector's
// selected-key set
t.channel.register(sel, SelectionKey.OP_CONNECT, t); } catch (IOException x) { // Something went wrong, so close the channel and
// record the failure
t.channel.close();
t.failure = x;
printer.add(t); } }
}
}