用Java实现的多线程扫描IP程序

java网络编程 专栏收录该内容
37 篇文章 0 订阅
import java.net.*;
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        PingTester tester = new PingTester();
        tester.startPing();
    }
}

class PingTester {
    private Queue<String> allIp;
    private int fetchedNum = 0; // 已经取得的任务数量,每次从队列中取一个ip就加1

    public PingTester() {
        // 首先创建一个队列用于存储所有ip地址
        allIp = new LinkedList<String>();
        for (int i = 0; i < 10; i++) {
            //allIp.offer("192.168.9." + i);
            for (int j = 0; j < 256; j++) {
                allIp.offer("192.168."+i+"."+j);
            }
        }
    }

    public void startPing() {
        // 创建一个线程池,多个线程同时跑
        int threadNum = 1000;
        ExecutorService executor = Executors.newFixedThreadPool(threadNum);
        for (int i = 0; i < threadNum; i++) {
            executor.execute(new PingRunner());
        }
        executor.shutdown();
        try {
            while (!executor.isTerminated()) {
                Thread.sleep(100);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Fetched num is "+fetchedNum);
    }

    private class PingRunner implements Runnable {
        private String taskIp = null;
        @Override
        public void run() {
            try {
                while ((taskIp = getIp()) != null) {
                    InetAddress addr = InetAddress.getByName(taskIp);
                    if (addr.isReachable(5000)) {
                        System.out.println("host ["+taskIp+"] is reachable");
                    } else {
                        System.out.println("host ["+taskIp+"] is not reachable");
                    }
                }
            } catch (SocketException e) {
                System.out.println("host ["+taskIp+"] permission denied");
            } catch (Exception e) {
                System.out.println("---------------------------------------------"+taskIp);
                e.printStackTrace();
            }
        }

        public String getIp() {
            String ip = null;
            synchronized (allIp) {
                ip = allIp.poll();
            }
            if (ip != null) {
                fetchedNum++;
            }
            return ip;
        }
    }
}
  • 0
    点赞
  • 0
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值