java 实现简单的端口扫描程序

实现思路:使用Socket类的connect(SocketAddress endpoint, int timeout) 方法,测试连接是否超时。使用多线程加快扫描速度。

package com.zhong.exam7;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 华韵流风
 */
public class ScanPort {
    static int threadNumber = 100;

    public static void main(String[] args) {
        long begin = System.currentTimeMillis();
        int portLeft = 3200;//端口下线
        int portRight = 3500;//端口上线
        int[] ports = new int[portRight - portLeft + 1];
        for (int i = portLeft; i <= portRight; i++) {
            ports[i - portLeft] = i;
        }//对端口进行逐个扫描
        ExecutorService pool = Executors.newFixedThreadPool(threadNumber);
        for (int i = 0; i < threadNumber; i++) {
            ScanMethod sm = new ScanMethod(threadNumber, i, ports, "127.0.0.1", 800);
            pool.execute(sm);
        }
        pool.shutdown();
        while (true) {
            if (pool.isTerminated()) {
                long end = System.currentTimeMillis();
                System.out.println("扫描结束,耗时:" + (end - begin));
                break;
            }
        }
    }
}

class ScanMethod implements Runnable {
    private int threadNumber;//线程总数
    private int serial;//当前线程编号
    private int[] ports;//端口号数组
    private String ip;//目标IP
    private final int timeout;


    public ScanMethod(int threadNumber, int serial, int[] ports, String ip, int timeout) {
        this.threadNumber = threadNumber;
        this.serial = serial;
        this.ports = ports;
        this.ip = ip;
        this.timeout = timeout;
    }

    @Override
    public void run() {
        try {
            Socket socket;
            SocketAddress sa;
            for (int i = serial; i < ports.length; i += threadNumber) {
                socket = new Socket();
                sa = new InetSocketAddress(ip, ports[i]);
                try {
                    socket.connect(sa, timeout);
                    socket.close();
                    System.out.println("端口:" + ports[i] + "——>开放");
                } catch (Exception e) {
                    System.out.println("端口:" + ports[i] + "——>正在使用或被关闭");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(java编程,java高级,案例,多线程,socket,java,端口扫描)