Главная » soft, programming » Programming » Javasamples.executesystemcommand.commandline.ping

Javasamples.executesystemcommand.commandline.ping

import java.io.*;
import java.util.*;
/**
 * A Java ping class. CALLING SYSTEM COMMANDS
 * Created by Alvin Alexander, devdaily.com.
 */
public class JavaPingExampleProgram
{
  public static void main(String args[])
  throws IOException
  {
    // create the ping command as a list of strings
    JavaPingExampleProgram ping = new JavaPingExampleProgram();
    List<String> commands = new ArrayList<String>();
    commands.add("/sbin/ping");
    commands.add("-c");
    commands.add("5");
    commands.add("www.google.com");
    ping.doCommand(commands);
  }
  /**
   * Provide the command you want to run as a List of Strings. Here's an example:
   *
   * List<String> commands = new ArrayList<String>();
   * commands.add("/sbin/ping");
   * commands.add("-c");
   * commands.add("5");
   * commands.add("www.google.com");
   * exec.doCommand(commands);
   *
   * @param command The command you want to execute, provided as List<String>.
   * @throws IOException This exception is thrown so you will know about it, and can deal with it.
   */
  public void doCommand(List<String> command)
  throws IOException
  {
    String s = null;
    
    ProcessBuilder pb = new ProcessBuilder(command);
    Process process = pb.start();
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    // read the output from the command
    System.out.println("Here is the standard output of the command:\n");
    while ((s = stdInput.readLine()) != null)
    {
      System.out.println(s);
    }
    // read any errors from the attempted command
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null)
    {
      System.out.println(s);
    }
  }
  /**
* on more sample

     */

privatestaticboolean ping(String host)throwsIOException,InterruptedException{
boolean isWindows =System.getProperty("os.name").toLowerCase().contains("win");
ProcessBuilder processBuilder =newProcessBuilder("ping", isWindows?"-n":"-c","1", host);
Process proc = processBuilder.start();
int returnVal = proc.waitFor();
return returnVal ==0;}
}

import java.io.*;

class CountFile {
public static void main(String args[])
throws java.io.IOException, java.io.FileNotFoundException
{
int count = 0;
InputStream is;

if (args.length == 1)
is = new FileInputStream(args[0]);
else
is = System.in;

while (is.read() != -1)
count++;

if (args.length == 1)
System.out.println(args[0] + » has «+ count + » chars.»);
else
System.out.println(«Input has » + count + » chars.»);
}
}
http://www.rgagnon.com/javadetails/java-0132.html —too old

publicstaticvoid main(String[] args)throwsUnknownHostException,IOException{String ipAddress ="127.0.0.1";InetAddress inet =InetAddress.getByName(ipAddress);System.out.println("Sending Ping Request to "+ ipAddress);System.out.println(inet.isReachable(5000)?"Host is reachable":"Host is NOT reachable");

    ipAddress ="173.194.32.38";
    inet =InetAddress.getByName(ipAddress);System.out.println("Sending Ping Request to "+ ipAddress);System.out.println(inet.isReachable(5000)?"Host is reachable":"Host is NOT reachable");}
//all reachable
publicstaticvoid main(String[] args)throwsUnknownHostException,IOException{InetAddress inet;

    inet =InetAddress.getByAddress(newbyte[]{127,0,0,1});System.out.println("Sending Ping Request to "+ inet);System.out.println(inet.isReachable(5000)?"Host is reachable":"Host is NOT reachable");

    inet =InetAddress.getByAddress(newbyte[]{(byte)173,(byte)194,32,38});System.out.println("Sending Ping Request to "+ inet);System.out.println(inet.isReachable(5000)?"Host is reachable":"Host is NOT reachable");}

http://www.dnsjava.org/
one does not simply ping in java69rl3

http://codereview.stackexchange.com/questions/38557/concurrent-multi-server-pinging-in-java —many samplesof  pinger
http://stackoverflow.com/questions/3584210/preferred-java-way-to-ping-a-http-url-for-availability —like earlier

Socket socket =null;boolean reachable =false;try{
    socket =newSocket(hostnameOrIP,80);
    reachable =true;}finally{if(socket !=null)try{ socket.close();}catch(IOException e){}}
boolean reachable =InetAddress.getByName(hostname).isReachable();
HttpURLConnection connection =(HttpURLConnection)new URL(url).openConnection();
connection.setRequestMethod("HEAD");int responseCode = connection.getResponseCode();if(responseCode !=200){// Not OK.}// < 100 is undetermined.// 1nn is informal (shouldn't happen on a GET/HEAD)// 2nn is success// 3nn is redirect// 4nn is client error// 5nn is server error

For more detail about response status codes see RFC 2616 section 10. Calling connect() is by the way not needed if you’re determining the response data. It will implicitly connect.

/**
* Pings a HTTP URL. This effectively sends a HEAD request and returns true if the response code is in
* the 200-399 range.
* @param url The HTTP URL to be pinged.
* @param timeout The timeout in millis for both the connection timeout and the response read timeout. Note that
* the total timeout is effectively two times the given timeout.
* @return true if the given HTTP URL has returned response code 200-399 on a HEAD request within the
* given timeout, otherwise false.
*/
public static boolean ping(String url, int timeout) {
url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.

try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.setRequestMethod(«HEAD»);
int responseCode = connection.getResponseCode();
return (200 <= responseCode && responseCode <= 399);
} catch (IOException exception) {
return false;
}
}

Restlet framework:
Client client = new Client(Protocol.HTTP);
Response response = client.get(url);
if (response.getStatus().isError()) {
// uh oh!
}

HttpURLConnection:
HttpURLConnection connection = null;
try {
URL u = new URL("http://www.google.com/");
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("HEAD");
int code = connection.getResponseCode();
System.out.println("" + code);
// You can determine on HTTP return code received. 200 is success.
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}

Реклама

Добавить комментарий

Заполните поля или щелкните по значку, чтобы оставить свой комментарий:

Логотип WordPress.com

Для комментария используется ваша учётная запись WordPress.com. Выход / Изменить )

Фотография Twitter

Для комментария используется ваша учётная запись Twitter. Выход / Изменить )

Фотография Facebook

Для комментария используется ваша учётная запись Facebook. Выход / Изменить )

Google+ photo

Для комментария используется ваша учётная запись Google+. Выход / Изменить )

Connecting to %s