java如何ping
使用 InetAddress 类进行 Ping 操作
Java 中可以通过 InetAddress 类的 isReachable 方法实现基础的 Ping 功能。该方法会发送 ICMP 请求或尝试建立 TCP 连接(端口 7,通常为 echo 服务)。
import java.net.InetAddress;
public class PingExample {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("example.com");
boolean reachable = address.isReachable(5000); // 超时时间 5 秒
System.out.println("Host is reachable: " + reachable);
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意事项:
- 需要处理
UnknownHostException和IOException。 - 部分操作系统或网络配置可能限制 ICMP 请求,导致
isReachable返回false。
使用 ProcessBuilder 调用系统命令
通过执行系统自带的 ping 命令(适用于 Windows/Linux/macOS),可以获取更详细的输出结果。
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SystemPingExample {
public static void main(String[] args) {
String host = "example.com";
String os = System.getProperty("os.name").toLowerCase();
String[] command = os.contains("win")
? new String[]{"cmd.exe", "/c", "ping -n 3 " + host}
: new String[]{"sh", "-c", "ping -c 3 " + host};
try {
Process process = new ProcessBuilder(command).start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream())
);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
参数说明:
- Windows 使用
ping -n 3发送 3 个数据包。 - Linux/macOS 使用
ping -c 3发送 3 个数据包。
使用第三方库(如 Apache Commons Net)
Apache Commons Net 库提供更专业的网络工具,包括 ICMP 功能。
Maven 依赖:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.9.0</version>
</dependency>
代码示例:

import org.apache.commons.net.util.SubnetUtils;
import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
public class CommonsNetPing {
public static void main(String[] args) {
try {
SubnetUtils utils = new SubnetUtils("192.168.1.0/24");
SubnetInfo info = utils.getInfo();
String[] addresses = info.getAllAddresses();
for (String ip : addresses) {
boolean reachable = InetAddress.getByName(ip).isReachable(1000);
System.out.println(ip + ": " + (reachable ? "Reachable" : "Unreachable"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意事项
- 权限问题:某些操作系统需要管理员权限才能执行 ICMP 请求。
- 防火墙设置:确保目标主机未屏蔽 ICMP 请求。
- 跨平台兼容性:不同操作系统对
ping命令的参数支持可能不同。






