Using Java to detect network connection status

Source: Internet
Author: User

In Windows, you can use the ping command in CMD to detect network connection conditions, as follows:

When the network connection is normal:


When the network is not connected:



In Java, you can call the ping command to determine whether the network is connected properly:

Package Module.system.common;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.InputStream; Import java.io.inputstreamreader;/** * Determine network connection status.    * @author NAGSH * */public class Netstate {public boolean isconnect () {Boolean connect = false;    Runtime runtime = Runtime.getruntime ();         Process Process;try {process = Runtime.exec ("ping" + "www.baidu.com"); InputStream is = Process.getinputstream ();         InputStreamReader ISR = new InputStreamReader (IS);         BufferedReader br = new BufferedReader (ISR);         String line = null;         StringBuffer sb = new StringBuffer ();         while (line = Br.readline ())! = null) {sb.append (line);          } System.out.println ("Return value:" +SB);         Is.close ();         Isr.close ();         Br.close ();             if (null! = SB &&!sb.tostring (). Equals ("")) {String logstring = ""; if (sb.tostring (). IndexOf ("TTL") > 0) {//network unblocked connect = True            } else {//network not unblocked connect = false;         }}} catch (IOException e) {e.printstacktrace ();}    return connect; }public static void Main (string[] args) {netstate netstate = new Netstate (); System.out.println (Netstate.isconnect ());}}







Using Java to detect network connection status

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: info-contact@alibabacloud.com 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.