java 判斷本機電腦是否能連接外網


java 判斷本機電腦是否能連接外網


String host = "202.108.22.5";
int timeOut = 3000; //超時應該在3鈔以上
boolean status = InetAddress.getByName(host).isReachable(timeOut);


當返回值是true時,說明host是可用的,反則不可。


//判斷ip、端口是否可連接 public static boolean isHostConnectable(String host, int port) { Socket socket = new Socket(); try { socket.connect(new InetSocketAddress(host, port)); } catch (IOException e) { e.printStackTrace(); return false; } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } return true; } //判斷ip是否可以連接 timeOut是超時時間 public static boolean isHostReachable(String host, Integer timeOut) { try { return InetAddress.getByName(host).isReachable(timeOut); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }


//測試URL地址是否能正常連接

public static int testWsdlConnection(String address) throws Exception {
     int status = 404;
     try {
         URL urlObj = new URL(address);
         HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
         oc.setUseCaches(false);
         oc.setConnectTimeout(3000); // 設置超時時間
         status = oc.getResponseCode();// 請求狀態
         if (200 == status) {
             // 200是請求地址順利連通。。
             return status;
         }
     } catch (Exception e) {
         e.printStackTrace();
         throw e;
     }
     return status;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM