Use java to check network connection status

Source: Internet
Author: User

Use java to check network connection status

In windows, you can use the ping command in cmd to check the network connection status, as shown below:

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 connection is normal:

Package module. system. common; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader;/*** determines the network connection status. * @ author nagsh **/public class NetState {public boolean isConnect () {boolean connect = false; Runtime runtime = Runtime. getRuntime (); Process process; try {process = runtime.exe c ("ping" + "www.baidu.com"); InputStream is = process. getindium UtStream (); 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) {// connect = true;} else {// connect = false;} catch (IOException e) {e. printStackTrace ();} return connect;} public static void main (String [] args) {NetState netState = new NetState (); System. out. println (netState. isConnect ());}}







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.