不同格式的ip 统一转成ip列表

支持以下格式的ip地址:

192.168.1.0/24

192.168.1.1-23

192.168.1.123

代码如下:

package finder;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

public class Util {

@SuppressWarnings("restriction")
public static ArrayList<String> stringToIps(String str) throws UnknownHostException {  //此方式主要是将各种格式的ip地址,转成ip列表,并以ArrayList<String>格式返回。

ArrayList<String> ips = new ArrayList<String>();  // 保存转换后的ip地址
String strIps[] = str.split(" ");

for (String string : strIps) {
if (sun.net.util.IPAddressUtil.isIPv4LiteralAddress(string)) {  // 校验是否为ip地址
ips.add(string);
} else if (string.lastIndexOf("-") != -1) {  // 判断是否为192.168.1.1-23这种格式
String iph[] = string.split("-");
if (sun.net.util.IPAddressUtil.isIPv4LiteralAddress(iph[0])) {
String x = iph[0];
String ipx[] = x.split("\.");
Integer start = Integer.parseInt(ipx[3]);
Integer end = Integer.parseInt(iph[1]);

while (start <= end) {
String ip = ipx[0] + "." + ipx[1] + "." + ipx[2] + "." + start.toString();
ips.add(ip);
start++;
}
}

} else if (str.lastIndexOf("/") != -1) {   // 判断是否为192.168.1.1/24这种格式
String iph[] = string.split("/");
if (sun.net.util.IPAddressUtil.isIPv4LiteralAddress(iph[0])) {
Integer mask = Integer.parseInt(iph[1]);
if (mask <= 32 && mask >= 1) {
ips.addAll(maskToIps(iph[0], mask));  // 将网络地址和掩码位数传给maskToIps函数 
}

}
} else {
ips.add(string);

}

}
return ips;

}

public static ArrayList<String> maskToIps(String ip, Integer m) throws UnknownHostException {   // 通过网络地址和掩码位数获取ip地址列表

ArrayList<String> i = new ArrayList<String>();

InetAddress inetAddress = InetAddress.getByName(ip);
int address = inetAddress.hashCode();
Integer n = 32 - m;
int startIp = (address & ((0xFFFFFFFF) << n)); // 最小ip地址
int endIp = (address | ((0xFFFFFFFF) >>> m)); //最大ip地址

while (startIp <= endIp) {

byte[] startaddr = getAddress(startIp);
InetAddress from = InetAddress.getByAddress(startaddr);
String fromIp = from.getHostAddress();
i.add(fromIp);
startIp++;
}

return i;
}

public static byte[] getAddress(int intIp) {  // 将整数ip地址转换成字节数组
int address = intIp;
byte[] addr = new byte[4];

addr[0] = (byte) ((address >>> 24) & 0xFF);
addr[1] = (byte) ((address >>> 16) & 0xFF);
addr[2] = (byte) ((address >>> 8) & 0xFF);
addr[3] = (byte) (address & 0xFF);
return addr;
}

public static ArrayList<Integer> stringToPorts(String str) {  // 这里是将各种格式的端口信息转成端口列表,比如 1-65535,80,8080,8000-9000
String ports[] = str.split(",");
ArrayList<Integer> portList = new ArrayList<Integer>();
for (String string : ports) {
if (string.lastIndexOf("-") != -1) {
String strPorts[] = string.split("-");
Integer startPort = Integer.parseInt(strPorts[0]);
Integer endPort = Integer.parseInt(strPorts[1]);
while (startPort <= endPort) {

if (startPort < 0 || startPort > 0xFFFF) {
portList.add(startPort);
startPort++;

}
}
} else {

Integer in = Integer.parseInt(string);
if (in > 0 && in < 0xFFFF) {
portList.add(in);

}

}

}
return portList;

}

}

原文地址:https://www.cnblogs.com/fsqsec/p/5459297.html