]> _ Git - cubist_net.git/commitdiff
wip #5265 @0.25
authorVincent Vanwaelscappel <vincent@cubedesigners.com>
Tue, 3 May 2022 07:33:01 +0000 (09:33 +0200)
committerVincent Vanwaelscappel <vincent@cubedesigners.com>
Tue, 3 May 2022 07:33:01 +0000 (09:33 +0200)
src/Util.php [new file with mode: 0644]

diff --git a/src/Util.php b/src/Util.php
new file mode 100644 (file)
index 0000000..d34c88e
--- /dev/null
@@ -0,0 +1,50 @@
+<?php
+
+namespace Cubist\Net;
+
+class Util
+{
+    public static function resolve($hostOrCIDR)
+    {
+        if (self::isValidCIDR($hostOrCIDR) || self::isValidIP($hostOrCIDR)) {
+            return $hostOrCIDR;
+        }
+        $res = gethostbyname($hostOrCIDR);
+        if ($res === $hostOrCIDR) {
+            return false;
+        }
+        return $res;
+    }
+
+    public static function isValidIP($str)
+    {
+        return filter_var($str, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
+    }
+
+    public static function isValidCIDR($cidr)
+    {
+
+        $parts = explode('/', $cidr);
+        if (count($parts) != 2) {
+            return false;
+        }
+
+        $ip = $parts[0];
+        $netmask = intval($parts[1]);
+
+        if ($netmask < 0) {
+            return false;
+        }
+
+        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
+            return $netmask <= 32;
+        }
+
+        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
+            return $netmask <= 128;
+        }
+
+        return false;
+    }
+
+}
\ No newline at end of file