Using Java to implement ping functions __java

Source: Internet
Author: User

See several forums have been asked to use Java to achieve the function of ping, if Google can also find a lot of answers. Someone uses the Java runtime.exec to invoke the system's ping command directly. Someone has also completed a pure Java implementation ping program, using Java NIO package (native IO, efficient IO package).

I personally think that there is no need to use Java to write a new ping command, because there is not much meaning. More people are concerned with using Java to implement ping to test whether a remote host is available. In fact, the functionality of ICMP Ping has been implemented since the Java 1.5, package. I will introduce the following:

Since Java 1.5, a method in
public boolean isreachable (int timeout) throws IOException

It implements the ICMP ECHO REQUEST.

Usage is as follows:

String host = ""
int timeOut = 3000; Timeout should be over 3 banknotes
Boolean status = Inetaddress.getbyname (host). Isreachable (TimeOut);

When the return value is true, the host is available and is not.

It should be noted that if the remote server has a firewall or associated configuration, it may affect the results and is unavoidable.

In addition, the Isreachable method attempts to connect to the TCP Port 7 (Echo) of the remote host, because the program has certain permissions to the system for sending ICMP requests, and when this permission is not satisfied.

Method Two

Use the runtime execute cmd command. This has the Chinese garbled problem, has not solved for the time being, later will say again.

Runtime Runtime = Runtime.getruntime ();

Process process = NULL;

String command = "Ping";

String str = "";

try {

Process = runtime.exec (command);

InputStreamReader InputStreamReader = new InputStreamReader (Process.getinputstream ());

Char[] by = new char[1024];

while ( (by)!=-1) {

System.out.println (A new String (by));

catch (IOException e) {

E.printstacktrace ();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.