Pregunta

I have list of ip addresses as string, but there are some subnets in that list too. For example:

... 127.0.0.1 (this is ip) 127.0.0.1/24 (this is subnet) ...

I want to check which is ip and which is subnet. So far I can filter ip but I couldn`t find a way to check subnet:

foreach ($ipstrings as $ip) {
        if(filter_var($ip, FILTER_VALIDATE_IP) !== false){
            $ips[] = $ip;
        }
        elseif (is_subnet) {
            $subnets[] = $ip;
        }
    }

How can make is_subnet work?

¿Fue útil?

Solución

<?php

// array of ip and subnets
$ipandmask = array('127.0.0.1','127.0.0.0','127.0.0.2','127.0.0.3/24','127.0.0.4/16'); 

foreach ($ipandmask as $ipmask) {

        if(preg_match('~^(?:[0-9]{1,3}\.){3}[0-9]{1,3}/[0-9][0-9]~',$ipmask,$subnet)){
        echo "</br>";
        echo "Subnet =>";
        print_r ($subnet);

    }

        if(preg_match('~^(?:[0-9]{1,3}\.){3}[0-9]{1,3}~',$ipmask,$ip)){
        echo "</br>";
        echo "Ip =>";
        print_r ($ip);

    }

}


    ?>

Otros consejos

You can do something like this:

$ip = '127.0.0.1/124';
$subnet = '';
if (preg_match('~^(.+?)/([^/]+)$~', $ip, $m)) {
   $ip = $m[1];
   $subnet = $m[2];
}
echo filter_var($ip, FILTER_VALIDATE_IP) . ", $subnet";

you can try this...

<?php
$ip="127.0.0.1/25";
$x = explode("/",$ip);
print_r($x);
if (isset($x[1])){
    echo"subnet";
} else {echo "ip";}
?>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top