JAVA功能代码-端口扫描

Java多线程端口扫描代码,扫描指定IP地址段内开放的端口

  • domain为IP地址,从startport端口开始,扫描到endport端口为止
public void test(String domain,int startport,int endport) {
    if (startport > endport){
        System.out.println("输入参数错误!");
        return;
    }
    int flag=0;
    LinkedList<Thread> threadPool = new LinkedList<Thread>();
    for (int i = startport ; i<endport ; i++ ){
        int port = i;
        Socket socket = new Socket();
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    socket.connect(new InetSocketAddress(domain,port));
                    System.out.println("端口"+port+":开放");
                } catch (IOException e) {
                    // System.out.println("端口"+port+":关闭");
                }
            }
        };
        flag++;
        Thread th = new Thread(run);
        th.start();
        threadPool.add(th);
    }
    Runnable runobserv = new Runnable() {
        @Override
        public void run() {
            boolean alljobisover = false;
            while (!alljobisover){
                alljobisover = true;
                for (Thread thread : threadPool){
                    if (thread.isAlive()){
                        alljobisover = false;
                        break;
                    }
                }
            }
        }
    };
    Thread t1 = new Thread(runobserv);
    t1.start();
    System.out.println("flag:"+flag);
}
本站有更新,点击刷新查看最新内容 ×