检测电脑是否连接网络呢?

java问题王 Java每日一问 发布时间:2021-10-06 18:07:02 阅读数:9355 1
下文是笔者收集:使用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
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaProblem/202110/1397.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者