Hi there,
Was wondering if you could help me out again. In my efforts to write a function to check whether an IPv6 address is part of an IPv6 prefix, I've come up with this:
PHP Code:
function isIPIn ($ip,$net,$mask)
{
$net = pack("H" . strlen($net), str_replace(":", "", $net));
$ip = pack("H" . strlen($ip), str_replace(":", "", $ip));
$binnet = str_pad ($net, 128, "0", "STR_PAD_LEFT");
$firstpart = substr($binnet, 0, $mask);
$binip = str_pad ($ip, 128, "0", "STR_PAD_LEFT");
$firstip = substr ($binip, 0, $mask);
return (strcmp ($firstpart, $firstip) == 0);
}
A number of things I'd like to clarify:
1. This code is based on a similar function I found dealing with IPv4 adresses.
2. I haven't taken into account the compressed format of IPv6 addresses yet. I'll get to that when I get this working.
3. To give a quick explanation of what I hope and think I'm doing in the function: I first try to convert the IPv6 hexadecimal address to binary.
4. I then fill it up to 128 bits (at least I think, but I'm actually not really sure if I need to)
5. Finally I compare chunks of the two addresses (based on the mask) to see if they match up. This actually checks whether the IPv6 address actually matches the prefix, I hope.
When I try the following:
PHP Code:
<?
$ip = "2000:0610:013A:0000:0000:0000:0000:0001";
$net = "2001:0610:013A:0000:0000:0000:0000:0000";
$mask = "48";
echo isIPIn ($ip, $net, $mask);
?>
it returns 1 (true), which it shouldn't (or should it?).
If someone could help me out here to see if my logic is right, that would be great. In any case, any help is greatly appreciated!