adseipsum
adseipsum

Reputation: 43

Ipv4 mapped Ipv6 validation

In the rfc4291

said, that first 80 bits of this type of Ipv4 mapped Ipv6 address is 0. How to check that with PHP? I need more quick and safe way to do that instead of regexp.

Upvotes: 1

Views: 307

Answers (1)

Sander Steffann
Sander Steffann

Reputation: 9978

The easiest way is to convert the address from printable to binary form with inet_pton. That will give you a string where every charter corresponds to 8 bits of the address. Checking if the first 80 bits are zero is then as simple as checking the first 10 characters of the returned string:

$addr = '::10.1.2.3';
$bytes = inet_pton($addr);
if (substr($bytes, 0, 10) == "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") {
  echo "Yes\n";
} else {
  echo "No\n";
}

Upvotes: 2

Related Questions