Skip to content

Commit

Permalink
Helpers: fixed ipMatch() for IPv4 [closes #61]
Browse files Browse the repository at this point in the history
  • Loading branch information
JanTvrdik committed Jun 10, 2015
1 parent bed8d02 commit ea94d28
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 10 deletions.
8 changes: 3 additions & 5 deletions src/Http/Helpers.php
Expand Up @@ -47,12 +47,10 @@ public static function ipMatch($ip, $mask)
$arr = [ip2long($ip), ip2long($mask)];
} else {
$arr = unpack('N*', inet_pton($ip) . inet_pton($mask));
$size = $size === '' ? 0 : $max - $size;
}
$bits = implode('', array_map(function ($n) {
return sprintf('%032b', $n);
}, $arr));
return substr($bits, 0, $max - $size) === substr($bits, $max, $max - $size);
$bits = implode('', array_map(function ($n) { return sprintf('%032b', $n); }, $arr));
$size = $size === '' ? $max : (int) $size;
return substr($bits, 0, $size) === substr($bits, $max, $size);
}


Expand Down
10 changes: 5 additions & 5 deletions tests/Http/Helpers.phpt
Expand Up @@ -14,11 +14,11 @@ require __DIR__ . '/../bootstrap.php';
test(function() {
Assert::true( Helpers::ipMatch('192.168.68.233', '192.168.68.233') );
Assert::false( Helpers::ipMatch('192.168.68.234', '192.168.68.233') );
Assert::true( Helpers::ipMatch('192.168.64.0', '192.168.68.233/12') );
Assert::false( Helpers::ipMatch('192.168.63.255', '192.168.68.233/12') );
Assert::true( Helpers::ipMatch('192.168.79.254', '192.168.68.233/12') );
Assert::false( Helpers::ipMatch('192.168.80.0', '192.168.68.233/12') );
Assert::true( Helpers::ipMatch('127.0.0.1', '192.168.68.233/32') );
Assert::true( Helpers::ipMatch('192.168.64.0', '192.168.68.233/20') );
Assert::false( Helpers::ipMatch('192.168.63.255', '192.168.68.233/20') );
Assert::true( Helpers::ipMatch('192.168.79.254', '192.168.68.233/20') );
Assert::false( Helpers::ipMatch('192.168.80.0', '192.168.68.233/20') );
Assert::true( Helpers::ipMatch('127.0.0.1', '192.168.68.233/0') );
Assert::false( Helpers::ipMatch('127.0.0.1', '192.168.68.233/33') );
});

Expand Down

0 comments on commit ea94d28

Please sign in to comment.