JAVA 根据开始和结束ip,计算中间的所有ip
JAVA 根据开始和结束ip,计算中间的所有ip
要计算两个IP地址之间的所有IP地址,你可以将IP地址转换为整数,然后使用循环来递增整数,并将每个整数转换回IP地址。以下是一个Java方法,它将两个IP地址字符串作为参数,并返回一个字符串数组,其中包含所有中间IP地址。
import java.util.ArrayList;
import java.util.List;
import java.net.InetAddress;
import java.io.UnsupportedEncodingException;
public class IpRangeCalculator {
public static String[] calculateIpRange(String startIp, String endIp) {
try {
InetAddress startInetAddress = InetAddress.getByName(startIp);
InetAddress endInetAddress = InetAddress.getByName(endIp);
byte[] startBytes = startInetAddress.getAddress();
byte[] endBytes = endInetAddress.getAddress();
List<String> ipList = new ArrayList<>();
for (int i = 0; i < startBytes.length; i++) {
for (int j = Integer.parseInt(startIp.split("\\.")[i]); j < Integer.parseInt(endIp.split("\\.")[i]); j++) {
byte[] tempBytes = startBytes.clone();
tempBytes[i] = (byte) j;
ipList.add(InetAddress.getByAddress(tempBytes).getHostAddress());
}
}
return ipList.toArray(new String[0]);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String startIp = "192.168.1.1";
String endIp = "192.168.1.5";
String[] ipRange = calculateIpRange(startIp, endIp);
for (String ip : ipRange) {
System.out.println(ip);
}
}
}
这个方法首先将起始IP地址和结束IP地址转换为InetAddress对象,然后获取它们的字节数组表示。对于IP地址的每个字节,它会遍历可能的值,为每个字节创建一个新的字节数组,并将其转换回IP地址,添加到结果列表中。最后,将列表转换为字符串数组并返回。
原文地址:https://blog.csdn.net/qq_38105536/article/details/142355868
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.kler.cn/a/312736.html 如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.kler.cn/a/312736.html 如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!