Solutions to IPV6 ip2long in php

Source: Internet
Author: User

In a 32-bit system, ip2long cannot be converted to IPv6, but you can convert ip2bin and bin2ip to IPv4 and IPv6. false is returned if it is invalid.

Instance Program

The Code is as follows: Copy code

<? Php
Function ip2bin ($ ip)
{
If (filter_var ($ ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 )! = False)
Return base_convert (ip2long ($ ip), 10, 2 );
If (filter_var ($ ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) = false)
Return false;
If ($ ip_n = inet_ton ($ ip) === false) return false;
$ Bits = 15; // 16x8 bit = 128bit (ipv6)
While ($ bits> = 0)
{
$ Bin = sprintf ("% 08b", (ord ($ ip_n [$ bits]);
$ Ipbin = $ bin. $ ipbin;
$ Bits --;
}
Return $ ipbin;
}


Function bin2ip ($ bin)
{
If (strlen ($ bin) <= 32) // 32 bits (ipv4)
Return long2ip (base_convert ($ bin, 2, 10 ));
If (strlen ($ bin )! = 128)
Return false;
$ Pad = 128-strlen ($ bin );
For ($ I = 1; $ I <= $ pad; $ I ++)
{
$ Bin = "0". $ bin;
}
$ Bits = 0;
While ($ bits <= 7)
{
$ Bin_part = substr ($ bin, ($ bits * 16), 16 );
$ Ipv6. = dechex (bindec ($ bin_part )).":";
$ Bits ++;
}
Return inet_ntop (inet_ton (substr ($ ipv6, 0,-1 )));
}
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.