java - IP 范围和端口扫描器

标签 java arrays ip

有人可以帮助我使用命令行检查具有特定 IP 地址范围的端口扫描器吗?我怎样才能确保使用该 IP 范围进行端口扫描。

args[0] 和 args[1] 用于 IP 地址范围,而 args[2] 和 args[3] 用于端口扫描器。

例如我运行“java Test 1.1.1.1 5 0 10” 该程序将检查端口 0 - 10 上从 1.1.1.1 到 1.1.1.5 的 IP

这是我的代码:

import java.util.concurrent.*;
import java.util.*;
import java.net.*;

// source http://stackoverflow.com/questions/11547082/fastest-way-to-scan-ports-with-java

public class Test 
{   
public static void main(String [] args) throws Exception
{
    final ExecutorService es = Executors.newFixedThreadPool(20);
    int bRange = 0; //Declare String called bRange with initial value of 0.
    int eRange = 0; //Declare String called eRange with initial value of 0.
    final int timeout = 200;

    //byte[] ipAddr = InetAddress.getByName(args[0]).getAddress();
    //byte[] ipAddr1 = InetAddress.getByName(args[1]).getAddress();
    String ipAddr = args[0];
    String ipAddr1 = args[1];


    if (args.length != 3)
    {   
        try
        {               
            bRange = Integer.parseInt(args[2]); //Assign value of second argument to bRange.
            eRange = Integer.parseInt(args[3]); //Assign value of third argument to eRange.
        }
        catch(NumberFormatException E) //If user enter invalid data.
        {
            System.out.println("You did not enter a valid number for arguments 2 and 3. Please try again with valid Integers.");
            System.exit(0);
        }

        boolean fcheck = true; //DEBUG ONLY CAN DELETE
        final List<Future<Boolean>> futures = new ArrayList<>(); 

        ArrayList<Integer> portRange = new ArrayList<Integer>((eRange - bRange)); //Declare an ArrayList of Integer values called portRange and set its initial size.

        //For loop to randomize scans.
        for(int port = bRange; port <= eRange; port++) 
        {
            portRange.add(port);

            //Use ArrayList of portRange and shuffle to go through each port number once.
            Collections.shuffle(portRange); //Shuffle portRange.

            int size = portRange.size(); //Declare Integer called size and assign value of portRange ArrayList size value.
            int randPort = portRange.get(size-1); //Assign the last index of portRange ArrayList to Integer variable randPort.

            System.out.println(randPort); //Show all the ports

            //int randTimeout = randInt(30, 2000); //Assign random value to randTimeout by running method randInt(). PartD

            futures.add(portIsOpen(es, ipAddr, randPort, timeout));

            portRange.remove(size - 1); //Remove last element in portRange ArrayList.
        }

        es.shutdown(); //Tell the executor service that it can't accept new tasks, but the already submitted tasks continue to run.
        int openPorts = 0; //Declare Integer called openPorts and assign value of 0.


        for(final Future<Boolean> f : futures)
        {
            if(f.get()) 
            {
                openPorts++;
            }
        }
        System.out.println("There are " + openPorts + " open ports on host " + ipAddr + " to " + ipAddr1 + " probed with a timeout of " + timeout + "ms");
        //Print statement show how many ports open based on the particular IP Address and the timeout.
    }       
    else
    {
        System.out.println("Wrong number of arguments");
        System.out.println("Please try again");
    }   
}

public static Future<Boolean> portIsOpen(final ExecutorService es, final String ipAddr, final int port, final int timeout)
{
    return es.submit(new Callable<Boolean>() 
    {
        @Override public Boolean call()
        {
            try //Try block, each time the For loop increments the Try block gets invoked.
            {
                Socket socket = new Socket(); //The Try block creates an instance of the Socket Class.
                socket.connect(new InetSocketAddress(ipAddr, port), timeout); //Create a stream socket and connects it to specified port number at the specified IP Address.
                socket.close(); //Close the socket connection.
                System.out.println("open port found " + port); //Result show how many ports are open.
                return true;
            }
            catch (Exception ex) 
            {
                return false;
            }
        }
    });
}
}

最佳答案

我想,使用通常的 CIDR 会好得多确定 ip 地址范围的符号。在这种情况下,您只需要使用一个附加参数,如 1.1.1.1/29,这意味着 ip 地址范围从 1.1.1.1 到 1.1.1.6,而 1.1.1.7 是广播地址.您可以使用 Apache Commons Net 类 SubnetUtils确定范围并获取所有包含的地址:

public static void main(String[] args) {    
    String subnet = "1.1.1.1/29";
    SubnetUtils utils = new SubnetUtils(subnet);
    String[] addresses = utils.getInfo().getAllAddresses();
    for (String ip : addresses) {
      System.out.println(ip);
    }
}

但现在看来,您的示例仅检查指定范围的第一个地址,因为您没有提供任何逻辑来迭代您提供的地址范围。

因此,如果您仍然希望按照以前的方式设置范围,则需要将范围表示法转换为具体地址列表,然后在此列表上添加一个额外的循环,并将其包含在端口上的循环中。

要获取此列表,您可以使用 getIpList 方法中的逻辑,只需要提供异常处理等:

public static List<String> getIpList(String startIp, int number) {
    List<String> result = new ArrayList<>();
    String currentIp = startIp;
    for (int i = 0; i < number; i++) {
        String nextIp = nextIpAddress(currentIp);
        result.add(nextIp);
        currentIp = nextIp;
    }
    return result;
}

public static final String nextIpAddress(final String input) {
    final String[] tokens = input.split("\\.");
    if (tokens.length != 4)
        throw new IllegalArgumentException();
    for (int i = tokens.length - 1; i >= 0; i--) {
        final int item = Integer.parseInt(tokens[i]);
        if (item < 255) {
            tokens[i] = String.valueOf(item + 1);
            for (int j = i + 1; j < 4; j++) {
                tokens[j] = "0";
            }
            break;
        }
    }
    return new StringBuilder()
            .append(tokens[0]).append('.')
            .append(tokens[1]).append('.')
            .append(tokens[2]).append('.')
            .append(tokens[3])
            .toString();
}

然后就可以得到范围内的IP列表,加一个循环:

List<String> ipRange = getIpList(ipAddr, ipAddr1);
for(String ipaddr : ipRange) {
  for (int port = bRange; port <= eRange; port++) {
    portRange.add(port);

    //Use ArrayList of portRange and shuffle to go through each port number once.
    Collections.shuffle(portRange); //Shuffle portRange.

    int size = portRange.size(); //Declare Integer called size and assign value of portRange ArrayList size value.
    int randPort = portRange.get(size - 1); //Assign the last index of portRange ArrayList to Integer variable randPort.

    System.out.println(randPort); //Show all the ports

    //int randTimeout = randInt(30, 2000); //Assign random value to randTimeout by running method randInt(). PartD

    futures.add(portIsOpen(es, ipaddr, randPort, timeout));

    portRange.remove(size - 1); //Remove last element in portRange ArrayList.
  }
}

关于java - IP 范围和端口扫描器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32941762/

相关文章:

docker - Docker群和Cloudflare DNS

java - 自定义剪贴板数据

java - 泛型需要类型转换

java - 使用maven的spring hibernate集成中的org.springframework.beans.factory.BeanCreationException

java - Eclipse 调试器,为特定(!)对象的字段设置观察点

c - 如何在 CUDA 中将包含数组的结构传递给内核?

java - 在java中对二维数组进行排序(对所有字母进行排序)

调用连接需要太多时间

c - 这是指向数组开头的指针的指针吗?

networking - 根据以下语句计算IP地址