Java多线程端口扫描程序

时间:2014-09-23 20:38:26

标签: java multithreading port synchronized

试图让它比现在更快。它的速度非常慢,线程似乎不会同时出现,无法弄明白。如果有人可以帮我描述我的问题在哪里,这样我就可以弄清楚如何让它变得更快我真的很感激它,非常感谢你!

package infoGrabber;

import java.awt.List;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class infoMain {

    public static int port;

    @SuppressWarnings("resource")
    public static void main(String[] args) {
        System.out.println("What host do you want to lookup?: ");
        Scanner userEntry = new Scanner(System.in);
        String host = userEntry.nextLine();

        try {
            startThreads(host);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private static void startThreads(String host) throws InterruptedException {
        int numThreads = 10;
        int count = 10;
        Thread[] threads = new Thread[numThreads];
        System.out.println("Creating threads");
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Runner(host, count));
            threads[i].start();
            threads[i].join();
        }
        System.out.println("Done");
    }
}

class Runner implements Runnable {
    static int port;
    private final String host;
    private final int count;
    infoMain main = new infoMain();

    public Runner(String host, int count) {
        this.host = host;
        this.count = count;
    }

    public void run() {
        for (int port = 0; port < 2000; port++) {
            // System.out.println(name + "=" + i + "\n");
            Socket socket;
                try {
                    socket = new Socket(host, port);// Attempt to establish a socket on port i.
                    // If no IOException thrown, there must
                    // be a service running on the port.
                    System.out.println("Port " + port + " is open.");
                    socket.close();
                } catch (IOException ioEx) {
                    System.out.println("Port " + port + " is not open.");
                }// No server on this port
            }
            Thread.yield();
        }
    }

1 个答案:

答案 0 :(得分:1)

您不会在线程之间划分工作。相反,您为每个线程提供相同数量的工作,就像您在顺序程序中给予主线程一样。你应该在你的线程之间划分工作,以提高执行速度。

您的循环应该类似于:

 for (int i = 0; i < threads.length; i++) {
     threads[i] = new Thread(new Runner(host, count * NUMBER_OF_PORTS_PER_THREAD));
     threads[i].start();

 }

 // Join threads after you created them
 // All credits for @biziclop for spotting this
 for (int i = 0; i < threads.length; i++) {
     threads[i].join();
 }

你的Runnable代码应该类似于:

class Runner implements Runnable {

final private int startPort;

public Runner(String host, int startPort) {
        this.host = host;
        this.startPort = startPort;
    }

    public void run() {
        for (int port = startPort; port <= NUMBER_OF_PORTS_PER_THREAD + startPort; port++) {
        ...
    }
}

其中NUMBER_OF_PORTS_PER_THREAD应该等于200以扫描具有10个线程的2000个端口。