2
0
forked from Wavyzz/dolibarr

Better function is_ip

This commit is contained in:
Laurent Destailleur
2014-07-26 14:16:09 +02:00
parent 8f6023ab5f
commit 3b9cfea8c9
2 changed files with 15 additions and 14 deletions

View File

@@ -1365,19 +1365,20 @@ function getListOfModels($db,$type,$maxfilenamelength=0)
* This function evaluates a string that should be a valid IPv4 * This function evaluates a string that should be a valid IPv4
* *
* @param string $ip IP Address * @param string $ip IP Address
* @return int 0 if not valid, 1 if valid and public IP, 2 if valid and private range IP * @return int 0 if not valid or reserved range, 1 if valid and public IP, 2 if valid and private range IP
*/ */
function is_ip($ip) function is_ip($ip)
{ {
//First we test if it is a valid IPv4 // First we test if it is a valid IPv4
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
//Then we test if it is not a private range // Then we test if it is a private range
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) { if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
return 1;
}
return 2; // Then we test if it is a reserved range
if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
return 1;
} }
return 0; return 0;

View File

@@ -161,11 +161,18 @@ class Functions2LibTest extends PHPUnit_Framework_TestCase
*/ */
public function testIsIP() public function testIsIP()
{ {
// Not valid
$ip='a299.299.299.299'; $ip='a299.299.299.299';
$result=is_ip($ip); $result=is_ip($ip);
print __METHOD__." for ".$ip." result=".$result."\n"; print __METHOD__." for ".$ip." result=".$result."\n";
$this->assertEquals(0,$result,$ip); $this->assertEquals(0,$result,$ip);
// Reserved IP range (not checked by is_ip function)
$ip='169.254.0.0';
$result=is_ip($ip);
print __METHOD__." for ".$ip." result=".$result."\n";
$this->assertEquals(0,$result,$ip);
$ip='1.2.3.4'; $ip='1.2.3.4';
$result=is_ip($ip); $result=is_ip($ip);
print __METHOD__." for ".$ip." result=".$result."\n"; print __METHOD__." for ".$ip." result=".$result."\n";
@@ -187,12 +194,5 @@ class Functions2LibTest extends PHPUnit_Framework_TestCase
print __METHOD__." for ".$ip." result=".$result."\n"; print __METHOD__." for ".$ip." result=".$result."\n";
$this->assertEquals(2,$result,$ip); $this->assertEquals(2,$result,$ip);
// Reserved IP range (not checked by is_ip function)
/*
$ip='169.254.0.0';
$result=is_ip($ip);
print __METHOD__." for ".$ip." result=".$result."\n";
$this->assertEquals(2,$result,$ip);
*/
} }
} }