当前位置: 首页 > news >正文

如何在 Java 程序中检查是否可以连接到某个网站

我们知道,如果我们想在终端检查是否可以连接到某个网站的时候,可以执行 ping 命令,直接 ping 某个网站,如果可以 ping 通,则表示可以连接上,例如:

ping baidu.comPinging baidu.com [220.181.7.203] with 32 bytes of data:
Reply from 220.181.7.203: bytes=32 time=47ms TTL=50
Reply from 220.181.7.203: bytes=32 time=46ms TTL=50
Reply from 220.181.7.203: bytes=32 time=46ms TTL=50
Reply from 220.181.7.203: bytes=32 time=46ms TTL=50Ping statistics for 220.181.7.203:Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:Minimum = 46ms, Maximum = 47ms, Average = 46ms

那么如果我们如何在 Java 程序中需要检查某个网站是否可以连接呢?从上面可以知道,我们可以 ping 一下某个网站就好了,可以使用 Runtime.getRuntime.exex("ping ") 的方式执行 ping 命令,但显然我们需要自己去维护输入输出流,从输入流中获取到 ping 命令执行的结果,从而解析到是否可以连接到某个网站。

显然采用执行命令的方式过于笨重,那么 Java 有没有直接提供 API 直接检测网站的可用性呢?

我们也知道,ping 命令其实是利用了 TCP/IP 模型下的 ICMP 协议,向目标地址请求一个回显数据包,并等待接受回显数据包,从而检测网站是否可用。因此在 Java 程序中只需要利用 ICMP 协议封装 API 即可实现类似 ping 的效果。

幸好,官方提供了这样的 API

// 根据网站实例化 InetAddress
val address = InetAddress.getByName(URL)
// 利用 isReachable 方法检查是否可以连通,TIMEOUT 则表示 超时时间
address.isReachable(TIMEOUT)

API 解释文档如下:

/*** Test whether that address is reachable. Best effort is made by the* implementation to try to reach the host, but firewalls and server* configuration may block requests resulting in a unreachable status* while some specific ports may be accessible.* A typical implementation will use ICMP ECHO REQUESTs if the* privilege can be obtained, otherwise it will try to establish* a TCP connection on port 7 (Echo) of the destination host.* <p>* The timeout value, in milliseconds, indicates the maximum amount of time* the try should take. If the operation times out before getting an* answer, the host is deemed unreachable. A negative value will result* in an IllegalArgumentException being thrown.** @param   timeout the time, in milliseconds, before the call aborts* @return a {@code boolean} indicating if the address is reachable.* @throws IOException if a network error occurs* @throws  IllegalArgumentException if {@code timeout} is negative.* @since 1.5*/
public boolean isReachable(int timeout)
http://www.dtcms.com/a/532844.html

相关文章:

  • 做网站市场报价步登顶wordpress小程序百家号
  • C语言复习笔记(一)
  • (10)shell 编程入门
  • 深入剖析C++文件操作的底层机制
  • 高端网站价格网架球加工厂家
  • 响应式网站文章网站建设字体变色代码
  • python+vue图书在线阅读推荐平台设计(源码+文档+调试+基础修改+答疑)
  • git仓库基本使用
  • 网站维护需要多久时间上海做网站建设公司排名
  • 在婚恋网站上做红娘怎么样什么都可以看的浏览器
  • 做平台网站要什么条件重庆网站建设重庆网站设计
  • 江苏系统建站怎么用咖啡网页设计素材
  • 网站建设软件免费使用密码访问wordpress文章
  • 物联网设备通信协议参数的能耗自适应调整机制
  • PySide6 win10 记事本从零到一——前言
  • win7 iis网站无法显示石家庄尚武科技
  • 建设网站哪家公司好网站建设公司招聘
  • UFS Reset 介绍
  • ESP8266无线开关
  • 生鲜电商网站建设一共有多少网站
  • 泰州网站建设案例海淘网站主要关键词
  • 网站 第三方登录做公众号用什么网站吗
  • 【FPGA】三八译码器——板级验证
  • Bugku-Web题目-charlottesweb- WolvCTF 2023
  • TCMalloc原理解析(下)
  • 短波红外相机入门核心场景和选型要求
  • centos做网站服务器吗南京品牌网站设计
  • 【Qt】启动新窗口--C/S传输信息
  • vf建设银行网站wordpress根据点击量最高查询文章
  • 统一日志管理架构设计