纯java实现 ping
时间: 2023-07-18 18:42:19 浏览: 55
在 Java 中,可以使用 `InetAddress` 类的 `isReachable()` 方法来实现 ping 命令。下面是一个简单的 Java 程序,演示了如何使用 `InetAddress` 类进行 ping 操作:
```java
import java.io.IOException;
import java.net.InetAddress;
public class PingExample {
public static void main(String[] args) {
try {
String host = "www.google.com";
InetAddress inetAddress = InetAddress.getByName(host);
boolean isReachable = inetAddress.isReachable(5000);
if (isReachable) {
System.out.println(host + " is reachable");
} else {
System.out.println(host + " is not reachable");
}
} catch (IOException ex) {
System.out.println("Exception: " + ex.getMessage());
}
}
}
```
在上面的示例中,我们使用了 `InetAddress` 类的 `getByName()` 方法来获取要 ping 的主机名或 IP 地址的 `InetAddress` 对象。然后,我们调用 `isReachable()` 方法,并传递一个超时时间(以毫秒为单位)。如果主机在超时时间内响应了 ping 请求,则 `isReachable()` 方法返回 `true`。否则,返回 `false`。最后,我们根据 `isReachable()` 方法的返回值输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)