Java PING IP 地址范围

Java PING a range of IP Address

Java ping 单个 IP 地址的程序

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 地址范围吗?

如果你只是想执行一个 bash 命令来 ping 一个范围,你最好使用 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());
        }
    }
}

这可以重构为更具体,但对于您的基本用户案例,这提供了一些灵活性。