六九博客-分享技术那些事六九博客-分享技术那些事

本博客仅做技术交流,
操作者不可用于违法用途!

IP检测PHP源码

免责声明:
本站资源并不针对任何人,任何机构,任何网站。
本站资源仅用于个人学习研究,请勿用于非法用途。
若因使用本站资源引起各类民事,刑事纠纷,属使用者的个人行为,与本站资源作者无关。
从你开始使用本服务,默认接受使用条款。
<?php

function ipv6($prefix= '2001:db8:abc:1400::/54'){
// Split in address and prefix length
list($firstaddrstr, $prefixlen) = explode('/', $prefix);

// Parse the address into a binary string
$firstaddrbin = inet_pton($firstaddrstr);

// Convert the binary string to a string with hexadecimal characters
# unpack() can be replaced with bin2hex()
# unpack() is used for symmetry with pack() below
$firstaddrhex = reset(unpack('H*', $firstaddrbin));

// Overwriting first address string to make sure notation is optimal
$firstaddrstr = inet_ntop($firstaddrbin);

// Calculate the number of 'flexible' bits
$flexbits = 128 - $prefixlen;

// Build the hexadecimal string of the last address
$lastaddrhex = $firstaddrhex;

// We start at the end of the string (which is always 32 characters long)
$pos = 31;
while ($flexbits > 0) {
  // Get the character at this position
  $orig = substr($lastaddrhex, $pos, 1);

  // Convert it to an integer
  $origval = hexdec($orig);

  // OR it with (2^flexbits)-1, with flexbits limited to 4 at a time
  $newval = $origval | (pow(2, min(4, $flexbits)) - 1);

  // Convert it back to a hexadecimal character
  $new = dechex($newval);

  // And put that character back in the string
  $lastaddrhex = substr_replace($lastaddrhex, $new, $pos, 1);

  // We processed one nibble, move to previous position
  $flexbits -= 4;
  $pos -= 1;
}

// Convert the hexadecimal string to a binary string
# Using pack() here
# Newer PHP version can use hex2bin()
$lastaddrbin = pack('H*', $lastaddrhex);

// And create an IPv6 address from the binary string
$lastaddrstr = inet_ntop($lastaddrbin);
return ['ipv6'=>$prefix,'first'=>$firstaddrstr,'last'=>$lastaddrstr];

}


function ip_parse($ip_str) {
 $mark_len = 32;
 if (strpos($ip_str, "/") > 0) {
  list($ip_str, $mark_len) = explode("/", $ip_str);
 }
 $ip = ip2long($ip_str);
 $mark = 0xFFFFFFFF << (32 - $mark_len) & 0xFFFFFFFF;
 $ip_start = $ip & $mark;
 $ip_end = $ip | (~$mark) & 0xFFFFFFFF;
 return array($ip, $mark, $ip_start, $ip_end);
}
//演示:
list($ip, $mark, $ip_start, $ip_end) = ip_parse("192.168.1.12/24");
echo "IP地址 : ", long2ip($ip), "\n";
echo "子网掩码: ", long2ip($mark), "\n";
echo "IP段开始: ", long2ip($ip_start), "\n";
echo "IP段结束: ", long2ip($ip_end), "\n";




function dtr_pton( $ip ){

    if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)){
        return current( unpack( "A4", inet_pton( $ip ) ) );
    }
    elseif(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)){
        return current( unpack( "A16", inet_pton( $ip ) ) );
    }else{
    return false;
    }
}

未经允许不得转载:六九博客-分享技术那些事 » IP检测PHP源码
添加新评论