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

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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值