天天看点

用JAVA实现一个简单的端口扫描功能

思路,使用socket对象的connect方法,输入准备扫描的主机名和端口号,根据方法执行阶段是否抛出异常来判断该端口能否正确访问,具体代码如下:

/**
     *
     * @param domain 主机域名或者IP
     * @param startport 开始端口
     * @param endport 结束端口
     */
    private static void  portScan(String domain,int startport,int endport){




        if (startport > endport){
            logger.error("输入参数错误!");
            return;
        }

        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));
                            logger.Info("端口"+port+":开放");
                        } catch (IOException e) {
/*                            if (port == 8888)
                                e.printStackTrace();
                            logger.Info("端口"+port+":关闭");*/
                        }
                    }
                };
                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();

    }