用于对单个IP地址执行ping操作的Java程序
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PingIP {
public static void runSystemCommand(String command) {
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
System.out.println(s);
}
....
}
但是我可以使用Java ping范围内的IP地址。
答案 0 :(得分:0)
如果您只是尝试执行可对范围进行ping操作的bash命令,则最好使用nmap
一个工作示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
final List<String> command = new ArrayList<>();
command.add("nmap");
command.add("-T5");
command.add("-sP");
command.add("172.19.0.0-255");
executeCommand(command);
}
private static int executeCommand(final List<String> command) {
try {
final ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash").command(command);
processBuilder.redirectErrorStream(true);
System.out.println("executing: " + processBuilder.command().toString());
final Process process = processBuilder.start();
final InputStream inputStream = process.getInputStream();
final InputStream errorStream = process.getErrorStream();
readStream(inputStream);
readStream(errorStream);
return process.waitFor();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return -1;
}
private static void readStream(final InputStream iStream) {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(iStream))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
可以将其重构为更具体的内容,但是对于您的基本用户情况,这提供了一定的灵活性。