珊瑚虫IP库浅析
这不是什么新鲜事情了,很早之前就已经有人做出来了。
就是使用PHP操作纯真IP库或珊瑚虫IP库,根据来访者的IP得到所在的物理位置。
我先帖出代码。然后再慢慢一步步浅析出来。希望对想了解这一块的朋友们有帮助。
Only For PHP5的代码。会继续优化代码的。
class IpLocation{
private $fp;
private $wrydat;
private $wrydat_version;
private $ipnumber;
private $firstip;
private $lastip;
private $ip_range_begin;
private $ip_range_end;
private $country;
private $area;
const REDIRECT_MODE_0 = 0;
const REDIRECT_MODE_1 = 1;
const REDIRECT_MODE_2 = 2;
function __construct(){
$args = func_get_args();
$this->wrydat = func_num_args()>0?$args[0]:'CoralWry.dat';
$this->initialize();
}
function __destruct(){
fclose($this->fp);
}
private function initialize(){
if(file_exists($this->wrydat))
$this->fp = fopen($this->wrydat,'rb');
$this->getipnumber();
$this->getwryversion();
}
public function get($str){
return $this->$str;
}
public function set($str,$val){
$this->$str = $val;
}
private function getbyte($length,$offset=null){
if(!is_null($offset)){
fseek($this->fp,$offset,SEEK_SET);
}
$b = fread($this->fp,$length);
return $b;
}
/**
* 把IP地址打包成二进制数据,以big endian(高位在前)格式打包
* 数据存储格式为 little endian(低位在前) 如:
* 00 28 C6 DA 218.198.40.0 little endian
* 3F 28 C6 DA 218.198.40.0 little endian
* 这样的数据无法作二分搜索查找的比较,所以必须先把获得的IP数据使用strrev转换为big endian
* @param $ip
* @return big endian格式的二进制数据
*/
private function packip($ip){
return pack( "N", intval( ip2long( $ip)));
}
private function getlong($length=4, $offset=null){
$chr=null;
for($c=0;$length%4!=0&&$c $chr .= chr(0);
}
$var = unpack( "Vlong", $this->getbyte($length, $offset).$chr);
return $var['long'];
}
private function getwryversion(){
$length = preg_match("/coral/i",$this->wrydat)?26:30;
$this->wrydat_version = $this->getbyte($length, $this->firstip-$length);
}
private function getipnumber(){
$this->firstip = $this->getlong();
$this->lastip = $this->getlong();
$this->ipnumber = ($this->lastip-$this->firstip)/7+1;
}
private function getstring($data="",$offset=null){
$char = $this->getbyte(1,$offset);
while(ord($char) > 0){
$data .= $char;
$char = $this->getbyte(1);
}
return $data;
}
private function iplocaltion($ip){
$ip = $this->packip($ip);
$low = 0;
$high = $this->ipnumber-1;
$ipposition = $this->lastip;
while($low $t = floor(($low+$high)/2);
if($ip getbyte(4,$this->firstip+$t*7))){
$high = $t - 1;
} else {
if($ip > strrev($this->getbyte(4,$this->getlong(3)))){
$low = $t + 1;
}else{
$ipposition = $this->firstip+$t*7;
break;
}
}
}
return $ipposition;
}
private function getarea(){
$b = $this->getbyte(1);
switch(ord($b)){
case self::REDIRECT_MODE_0 :
return "未知";
break;
case self::REDIRECT_MODE_1:
case self::REDIRECT_MODE_2:
return $this->getstring("",$this->getlong(3));
break;
default:
return $this->getstring($b);
break;
}
}
public function getiplocation($ip){
$ippos = $this->iplocaltion($ip);
$this->ip_range_begin = long2ip($this->getlong(4,$ippos));
$this->ip_range_end = long2ip($this->getlong(4,$this->getlong(3)));
$b = $this->getbyte(1);
switch (ord($b)){
case self::REDIRECT_MODE_1:
$b = $this->getbyte(1,$this->getlong(3));
if(ord($b) == REDIRECT_MODE_2){
$countryoffset = $this->getlong(3);
$this->area = $this->getarea();
$this->country = $this->getstring("",$countryoffset);
}else{
$this->country = $this->getstring($b);
$this->area = $this->getarea();
}
break;
case self::REDIRECT_MODE_2:
$countryoffset = $this->getlong(3);
$this->area = $this->getarea();
$this->country = $this->getstring("",$countryoffset);
break;
default:
$this->country = $this->getstring($b);
$this->area = $this->getarea();
break;
}
}
}
/* */
echo microtime();
echo "\n";
$iploca = new IpLocation;
//$iploca = new IpLocation('QQWry.dat');
echo $iploca->get('wrydat_version');
echo "\n";
echo $iploca->get('ipnumber');
echo "\n";
$iploca->getiplocation('211.44.32.34');
/**/
echo $iploca->get('ip_range_begin');
echo "\n";
echo $iploca->get('ip_range_end');
echo "\n";
echo $iploca->get('country');
echo "\n";
echo $iploca->get('area');
echo "\n";
echo $iploca->get('lastip');
echo "\n";
echo microtime();
echo "\n";
unset($iploca);
参考资料:LumaQQ的 纯真IP数据库格式详解
CoralWry.dat文件结构上分为3个区域:
- 文件头[固定8个字节]
- 数据区[不固定长度,记录IP的地址信息]
- 索引区[大小由文件头决定]
该文件数据的存储方式是:little endian。
在这里引用了谈谈Unicode编码里的关于little endian 与 big endian的区别
引用:
big endian和little endian是CPU处理多字节数的不同方式。例如“汉”字的Unicode编码是6C49。那么写到文件里时,究竟是将6C写在前面,还是将49写在前面?如果将6C写在前面,就是big endian。还是将49写在前面,就是little endian。
“endian”这个词出自《格列佛游记》。小人国的内战就源于吃鸡蛋时是究竟从大头(Big-Endian)敲开还是从小头(Little-Endian)敲开,由此曾发生过六次叛乱,其中一个皇帝送了命,另一个丢了王位。
我们一般将endian翻译成“字节序”,将big endian和little endian称作“大尾”和“小尾”。
文件头:
红色框框里的就是文件头,前4个字节是索引区的开始地址,后4个字节是索引区的结束地址。
如下图所示:
点击放大
由于数据库是使用了little endian的字节库,所以我们需要把它倒过来。
把文件头的0-3的字节读取出来,再使用 unpack 函数把二进制数据转换为big endian格式的无符号整型。
处理后,索引区的开始地址位置是:00077450 ;索引区的结束地址位置是:000CE17C。
如果你手头上有UltraEdit的软件,可以打开CoralWry.dat文件,查找地址为:00077450 的位置,那就是IP地址索引区的开始。
如下图所示:
点击放大
红色框框住那就是索引区的开始位置。

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

숙련된 PHP 개발자라면 이미 그런 일을 해왔다는 느낌을 받을 것입니다. 귀하는 상당한 수의 애플리케이션을 개발하고, 수백만 줄의 코드를 디버깅하고, 여러 스크립트를 수정하여 작업을 수행했습니다.

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.

PHP의 마법 방법은 무엇입니까? PHP의 마법 방법은 다음과 같습니다. 1. \ _ \ _ Construct, 객체를 초기화하는 데 사용됩니다. 2. \ _ \ _ 파괴, 자원을 정리하는 데 사용됩니다. 3. \ _ \ _ 호출, 존재하지 않는 메소드 호출을 처리하십시오. 4. \ _ \ _ get, 동적 속성 액세스를 구현하십시오. 5. \ _ \ _ Set, 동적 속성 설정을 구현하십시오. 이러한 방법은 특정 상황에서 자동으로 호출되어 코드 유연성과 효율성을 향상시킵니다.
