java 如何在给定开始和结束 IP 地址的情况下生成 IP 地址范围?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7303720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:28:43  来源:igfitidea点击:

How do I get generate an IP address range given start and end IP address?

java

提问by Vishal

How can generate a range of IP addresses from a start and end IP address?

如何从开始和结束 IP 地址生成一系列 IP 地址?

Example for a network "192.168.0.0/24":

网络“192.168.0.0/24”的示例:

String start = "192.168.0.2"
String end = "192.168.0.254"

I want to have:

我希望有:

192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
...
192.168.0.254

PS: Network, start and end IP can be dynamic above is just an example.

PS:网络,开始和结束IP可以是动态的,上面只是一个例子。

Thanks...

谢谢...

回答by Eric J.

Recognize that each of the 4 components of an IPv4 address is really a hex number between 00 and FF.

认识到 IPv4 地址的 4 个组成部分中的每一个实际上都是一个介于 00 和 FF 之间的十六进制数。

If you change your start and end IP addresses into 32 bit unsigned integers, you can just loop from the lowest one to the highest one and convert each value you loop through back into the IP address format.

如果将起始 IP 地址和结束 IP 地址更改为 32 位无符号整数,则只需从最低的一个循环到最高的一个,然后将循环的每个值转换回 IP 地址格式。

The range in the example you give is C0A80002 to C0A800FE.

您给出的示例中的范围是 C0A80002 到 C0A800FE。

Here's a link to code that converts between a hex number and an IPv4 address

这是在十六进制数和 IPv4 地址之间转换的代码的链接

http://technojeeves.com/joomla/index.php/free/58-convert-ip-address-to-number

http://technojeeves.com/joomla/index.php/free/58-convert-ip-address-to-number

回答by Bohemian

Here's simple implementation that outputs what you asked for:

这是输出您要求的简单实现:

public static void main(String args[]) {
    String start = "192.168.0.2";
    String end = "192.168.0.254";

    String[] startParts = start.split("(?<=\.)(?!.*\.)");
    String[] endParts = end.split("(?<=\.)(?!.*\.)");

    int first = Integer.parseInt(startParts[1]);
    int last = Integer.parseInt(endParts[1]);

    for (int i = first; i <= last; i++) {
        System.out.println(startParts[0] + i);
    }
}

Note that this will onlywork for ranges involving the lastpart of the IP address.

请注意,这适用于涉及IP 地址最后一部分的范围。

回答by Ryan Stewart

Start at 2, count to 254, and put a "192.168.0." in front of it:

从 2 开始,数到 254,然后输入“192.168.0”。在它面前:

for (int i = 2; i <= 254; i++) {
    System.out.println("192.168.0." + i);
}

回答by Vikas

void main(String args[]) 
{
String start = "192.168.0.2";
String end = "192.168.0.254";

String[] startParts = start.split("(?<=\.)(?!.*\.)");
String[] endParts = end.split("(?<=\.)(?!.*\.)");

int first = Integer.parseInt(startParts[1]);
int last = Integer.parseInt(endParts[1]);

for (int i = first; i <= last; i++) 
{
System.out.println(startParts[0] + i);
}
}