(2)得到ip地址后的处理过程
如下是搜索后台已经处理后的数据,
而对应的ip则是用户访问日志中的ip
当搜索后台得到用户的ip后,就会到后台查询对应的位置,例如,用户ip为116.205.128.0/13 则应当得到Hunan Tietongdaodianxin信息
后台日志test.log
116.205.128.0/17 Hunan Tietongdaodianxin
118.126.64.0/18 Hunan Tietongdaodianxin
处理程序如下:
cat ipanalyse.php
#!/usr/local/bin/php
<?php
function mask2bin($n){
$n = intval($n);
if( $n < 0 || $n > 32 ){
die( 'error submask ');
}
return str_repeat( "1", $n).str_repeat( "0",32-$n);
}
function execIp($str, &$ipdict) {
list($ip, $m) = explode( "/", $str);
$long = ip2long($ip);
$bIp = decbin("$long");
$bSub = mask2bin($m);
$sIp = $bIp & $bSub;
$val = bindec($sIp);
$ipdict[$val]["mask"] = $bSub;
return $val;
}
function loadiplib($fstr) {
$ipdict = array();
$ex = explode("\n", $fstr);
foreach($ex as $idx=> $val) {
$sp = explode("\t", $val);
$ipint = trim($sp[0]);
$ipcity = trim($sp[1]);
$ipsel = trim($sp[2]);
$ret = execIp($ipint, $ipdict);
$ipdict[$ret]["city"] = $ipcity;
$ipdict[$ret]["sel"] = $ipsel;
}
return $ipdict;
}
function ipsatisfycond(&$ip, &$ipdict) {
$long = ip2long($ip);
$bIp = decbin("$long");
foreach($ipdict as $int => $arr) {
$mask = trim($arr["mask"]);
$sIp = $bIp & $mask;
$val = bindec($sIp);
if($val == $int) {
return $arr["sel"];
}
}
return false;
}
/// main //
while(!feof(STDIN)){
$buf = fgets(STDIN);
$buf = trim($buf);
if(false === $buf || "" == $buf){
continue;
}
$ret = loadiplib($buf);
print_r($ret);
$ip = "116.205.128.0/13";
$res = ipsatisfycond($ip,$ret);
print_r($res);
}
?>
测试如下:
cat test.log | ./ipanalyse.php
输出为:
Array
(
[1959624704] => Array
(
[mask] => 11111111111111111000000000000000
[city] => Hunan
[sel] => Tietongdaodianxin
)
)
Array
(
[1987985408] => Array
(
[mask] => 11111111111111111100000000000000
[city] => Hunan
[sel] => Tietongdaodianxin
)
)
看输出的第二个array是不是程序中红色的ip的应该对应的信息呢?
这样针对ip这块基本用途就告一段落?,
下面介绍下:为什么搜索的第一页比后面的好?
待续