检测电脑是否连接网络呢?
下文是笔者收集:使用java代码检测当前环境是否连接成功Internet的方法分享,如下所示:
网络是否连通的示例分享
实现思路:
借助URL类的相关方法
openStream()是否可获取值
如能获取值,则代表网络状态联通
例:网络是否连通的示例分享
package com.java265.other;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URL;
public class Test {
/*
* java265.com 检测电脑是否连接Internet的示例分享
*/
private static String remoteInetAddr = "23.254.230.95";// 需要连接的IP地址
public static void main(String[] args) throws Exception {
URL url = null;
Boolean flag = false;
try {
url = new URL("http://baidu.com/");
InputStream in = url.openStream();// 检测是否可以正常连接baidu
System.out.println("连接正常");
in.close();
} catch (IOException e) {
System.out.println("无法连接到:" + url.toString());
}
flag = isReachable(remoteInetAddr);
System.out.println("pingIP:" + flag);
}
public static boolean isReachable(String remoteInetAddr) {
boolean reachable = false;
try {
InetAddress address = InetAddress.getByName(remoteInetAddr);
reachable = address.isReachable(5000);
} catch (Exception e) {
e.printStackTrace();
}
return reachable;
}
}
--------运行以上代码,将输出以下信息------
连接正常
ping:true
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


