Created
February 21, 2020 07:25
-
-
Save zhoulifu/7cdb513c83f719412c103c4096b5f5e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Objects; | |
import java.util.regex.Pattern; | |
class IPRangeExpander { | |
private static final Pattern IPV4_PATTERN = Pattern.compile("^(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){1}(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){2}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"); | |
public void expand(String from, String to) { | |
if (from == null || to == null) { | |
throw new IllegalArgumentException( | |
"Invalid ip range: from " + from + " to " + to); | |
} | |
long floor = inet_aton(from); | |
long ceil = inet_aton(to); | |
if (floor > ceil) { | |
throw new IllegalArgumentException( | |
"Invalid ip range: from " + from + " to " + to); | |
} | |
long count = ceil - floor + 1; | |
long step, tmp; | |
int prefix; | |
while (count > 0) { | |
step = floor & -floor; | |
while (step > count) { | |
step >>= 1; | |
} | |
tmp = step; | |
prefix = 33; | |
while (tmp > 0) { | |
prefix--; | |
tmp >>= 1; | |
} | |
System.out.println(inet_ntoa(floor) + "/" + prefix); | |
count -= step; | |
floor += step; | |
} | |
} | |
public static long inet_aton(String ipv4) { | |
Objects.requireNonNull(ipv4, "ip"); | |
if (!IPV4_PATTERN.matcher(ipv4).matches()) { | |
throw new IllegalArgumentException("Only ipv4 address supported"); | |
} | |
String[] parts = ipv4.split("\\."); | |
return (Integer.parseInt(parts[0]) & 0XFFL) << 24 | |
| (Integer.parseInt(parts[1]) & 0XFFL) << 16 | |
| (Integer.parseInt(parts[2]) & 0XFFL) << 8 | |
| Integer.parseInt(parts[3]) & 0XFFL; | |
} | |
public static String inet_ntoa(long numeric) { | |
return ((numeric >>> 24) & 0XFF) + "." + | |
((numeric >>> 16) & 0XFF) + "." + | |
((numeric >>> 8) & 0XFF) + "." + | |
(numeric & 0XFF); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment