summaryrefslogtreecommitdiff
path: root/module/ri-engine/src/main/java/io/trygvis/rules/network/IpCalc.java
diff options
context:
space:
mode:
Diffstat (limited to 'module/ri-engine/src/main/java/io/trygvis/rules/network/IpCalc.java')
-rw-r--r--module/ri-engine/src/main/java/io/trygvis/rules/network/IpCalc.java51
1 files changed, 51 insertions, 0 deletions
diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/network/IpCalc.java b/module/ri-engine/src/main/java/io/trygvis/rules/network/IpCalc.java
new file mode 100644
index 0000000..e40e169
--- /dev/null
+++ b/module/ri-engine/src/main/java/io/trygvis/rules/network/IpCalc.java
@@ -0,0 +1,51 @@
+package io.trygvis.rules.network;
+
+import java.util.regex.Pattern;
+
+public class IpCalc {
+ private static final Pattern pattern = Pattern.compile("([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})/([0-9]{1,3})");
+
+ public static Ipv4Cidr cidr(String cidr) {
+ var matcher = pattern.matcher(cidr);
+ if (!matcher.matches()) {
+ throw new IllegalArgumentException("Not a CIDR: " + cidr);
+ }
+
+ var b1 = matcher.group(1);
+ var b2 = matcher.group(2);
+ var b3 = matcher.group(3);
+ var b4 = matcher.group(4);
+
+ int network = parse(b1) << 24 |
+ parse(b2) << 16 |
+ parse(b3) << 8 |
+ parse(b4);
+
+// System.out.printf("network = %x%n", network);
+
+ var l = matcher.group(5);
+ var bits = Integer.parseInt(l);
+ var hostBits = 32 - bits;
+ int size = 1 << hostBits;
+
+ int netmask = (-1 >> hostBits) << hostBits;
+// System.out.printf("netmask = %08x%n", netmask);
+
+ int x = network & ~netmask;
+
+ if (x != 0) {
+ throw new IllegalArgumentException("Not a CIDR: " + cidr);
+ }
+
+ return new Ipv4Cidr(network, netmask, size, bits);
+ }
+
+ private static int parse(String s) {
+ var i = Integer.parseInt(s);
+ if (i > 255) {
+ throw new IllegalArgumentException("Not a CIDR");
+ }
+
+ return i;
+ }
+}