php manually implement ip2long and long2ip

php manually implement ip2long and long2ip

    /**
     * 测试
     */
    public function testipAction() {
        $ip = '10.58.101.175';
        echo ip2long($ip);
        echo "<br>";
        echo $this->myip2long($ip);
        echo "<br>";
        echo long2ip('171599279');
        echo "<br>";
        echo $this->mylong2ip('171599279');

    
     * @Param $ IP*/ *
    }
     * Realize his ip2long
     @Return a float * | int | String 
     * / 
    protected   function myip2long ( $ ip ) {
         $ newhex = '' ;
         // the ip divided into an array 
        $ ipsArr = the explode ( '',. $ Ip ;)
         the foreach ( $ ipsArr  AS  $ Key => $ value ) {
             // decimal maximum value is 255, and if it exceeds, the process directly returns 
            IF ( $ value > 255 ) {
                 return '' ; 
            } 
            // decimal conversion of hexadecimal 
            $ hex = dechex ( $ value );
             // for each maximum is 255 ip, the FF hexadecimal is, the maximum is two 
            @ example ip: 1.1.1.1 If no fill 0, 1111 is the hexadecimal, decimal is 4369 
            // 0 if the fill, the hex is 01010101, the decimal is 16,843,009 
            IF ( strlen ( $ hex ) <2 ) {
                 // If the length is less than 2 hex, automatically fill 0 
                $ hex = '0' . $ hex ; 
            } 
            $ newhex =. $ hex ; 
        } 
        // hexadecimal to decimal conversion 
        $ intStr = hexdec ( $ newhex );
         return  $ intStr ;
    } 

    / *  *
     * Realize his long2ip 
     * @param $ int 
     * @return String 
     * / 
    protected  function   mylong2ip ( $ int ) {
         //   FFFFFF maximum of 4294967295 
        $ int = $ int > 4294967295 4294967295:? $ Int ;
         // decimal turn hexadecimal 
        $ hex = dechex ( $ int );
         // to avoid occurrence ip 7, we manually fill 0 
        IF ( strlen ( $ hex ) <8 ) {
             // length is less than 8, the auto-fill 0 
            $ hex = '0'. $ hex ; 
        }
        // grouped every two. Then each group to see whether the first bit is 0, if it is then removed. The value obtained is then converted to decimal in the array, the array with the last connected. 
        For ( $ I = 0; $ I <. 8; $ I + = 2 ) {
             $ A = substr ( $ hex , $ I , 2 );
             $ ippart = substr ( $ A , 0,. 1 );
             IF ( $ ippart === '0' ) {
                 $ A = substr ( $ A ,. 1,. 1 ); 
            } 
            $ aparr [] = hexdec ( $ a);
        }
        return implode('.', $aparr);
    }

 

Guess you like

Origin www.cnblogs.com/justdoyou/p/11793334.html