簡體   English   中英

IP地址范圍

[英]IP Address in a range

有人可以在這里幫助解決問題嗎? 我想使用命令行檢查特定范圍內的IP地址。

例如,我在cmd“ java IPAddressCheck 1.1.1.1 5”中運行程序,輸出應為:

1.1.1.1
1.1.1.2
1.1.1.3
1.1.1.4
1.1.1.5

這是我的代碼,問題去了,我運行代碼,它將以“ 1.1.1.2”開頭,直到“ 1.1.1.6”為止。

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


public class IPAddressCheck 
{
public static void main(String[] args) throws Exception
{
        String startIp = args[0];
        int number = 0;

        if (args.length != 1)
        {
            try
            {
                number = Integer.parseInt(args[1]);
            }
            catch(IllegalArgumentException e)
            {
                System.out.println("Error");
                System.exit(0);
            }

            ArrayList<String> ipRange = new ArrayList<>();
            String currentIp = startIp;

            for(int i = 0; i < number; i++) 
            {
                String nextIp = nextIpAddress(currentIp);
                ipRange.add(nextIp);
                currentIp = nextIp;
                //System.out.println("----------------------------------");
                System.out.println(nextIp);
            }   
        }
        else
        {
            System.out.println("Wrong number of arguments");
            System.out.println("Please try again");
        }
}


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地址初始化范圍,然后使迭代次數等於addresss-1,因為列表中已經有一個地址:

ipRange.add(currentIp);
for(int i = 0; i < number-1; i++) 
{
    currentIp = nextIpAddress(currentIp);
    ipRange.add(currentIp);
}

很高興看到您發現我的回答有用))

這很簡單。 您的對帳單順序過早更改了IP。 編輯您的for循環,如下所示:

        System.out.println(currentIp);
        ipRange.add(currentIp);
        for(int i = 1; i < number; i++) 
        {
            currentIp = nextIpAddress(currentIp);
            ipRange.add(currentIp);
            System.out.println(currentIp);
        }   

首先,您的currentIp是您也要顯示的起始IP。 您可以輸出它,然后從第二個地址開始循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM