search
HomeBackend DevelopmentPHP TutorialDetailed explanation of how to convert IP address to real address in PHP_PHP Tutorial

Detailed explanation of how to convert IP address to real address in PHP_PHP Tutorial

Jul 21, 2016 pm 03:07 PM
ipv4phpBusinessaddressdatabasemethodofrealityDetailed explanationConvert

If you want to convert an IPv4 address to a real address, you must refer to the IP database. The commercial IP database is stored in a relational database. It is very convenient to query and use, but the cost is not what individuals and small companies are willing to bear, so it is simple to apply. The idea is to use some free IP databases or query APIs provided by some large websites. Their data volume is enough for us to use.
1. Use the Innocence IP database
Use the local QQWry.Dat file. The advantage is that the query speed is very fast. The disadvantage is that the database file must be placed in its own space. And update the database occasionally. Without further ado due to time constraints, here is the function that uses this file. If you are using this function in WordPress, write the following code into functions.php under the theme, and then in the comments-list output That's it; if it is referenced by other programs, enter a valid IPv4 address to get a real address.

Copy code The code is as follows:

function convertip($ip) {
//IP data file path
$dat_path = 'QQWry.Dat';
//Check IP address
//if(! preg_match("/^d{1,3}.d{1,3}.d{1,3}.d{1,3}$/", $ip)) {
// return 'IP Address Error';
//}
//Open IP data file
if(!$fd = @fopen($dat_path, 'rb')){
return 'IP date file not exists or access denied';
}
//Decompose the IP for operation and obtain an integer number
$ip = explode('.', $ip);
$ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];
//Get the start and end position of IP data index
$DataBegin = fread($fd, 4) ;
$DataEnd = fread($fd, 4);
$ipbegin = implode('', unpack('L', $DataBegin));
if($ipbegin $ipend = implode('', unpack('L', $DataEnd));
if($ipend $ipAllNum = ($ipend - $ipbegin) / 7 + 1;
$BeginNum = 0;
$EndNum = $ipAllNum;
//Use binary search method to record from the index Search for matching IP records in
while($ip1num>$ipNum || $ip2num $Middle= intval(($EndNum + $BeginNum) / 2);
//Partial Move the pointer to the index position and read 4 bytes
fseek($fd, $ipbegin + 7 * $Middle);
$ipData1 = fread($fd, 4);
if(strlen($ ipdata1) & lt; 4) {
fclose ($ fd);
Return 'System Error';
}
// The data extracted data conversion and plastic surgery. 32nd power
$ip1num = implode('', unpack('L', $ipData1));
if($ip1num                                                                                                                                                                                    ​>}
// After taking the previous index, remove a index
$ dataseek = FREAD ($ fd, 3);
if (strong ($ dataseek) & lt; 3) {
fclose ($fd);
           return 'System Error'; $fd, $DataSeek);
              $ipData2 = fread($fd, 4);                                                                                                                                                                   System Error';
}
$ip2num = implode('', unpack('L', $ipData2));
if($ip2num //Unknown prompt not found
if($ip2num return 'Unknown';
}

    $ipFlag = fread($fd, 1);
    if($ipFlag == chr(1)) {
        $ipSeek = fread($fd, 3);
        if(strlen($ipSeek)             fclose($fd);
            return 'System Error';
        }
        $ipSeek = implode('', unpack('L', $ipSeek.chr(0)));
        fseek($fd, $ipSeek);
        $ipFlag = fread($fd, 1);
    }
    if($ipFlag == chr(2)) {
        $AddrSeek = fread($fd, 3);
        if(strlen($AddrSeek)             fclose($fd);
            return 'System Error';
        }
        $ipFlag = fread($fd, 1);
        if($ipFlag == chr(2)) {
            $AddrSeek2 = fread($fd, 3);
            if(strlen($AddrSeek2)                 fclose($fd);
                return 'System Error';
            }
            $AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
            fseek($fd, $AddrSeek2);
        } else {
            fseek($fd, -1, SEEK_CUR);
        }
        while(($char = fread($fd, 1)) != chr(0))
            $ipAddr2 .= $char;
        $AddrSeek = implode('', unpack('L', $AddrSeek.chr(0)));
        fseek($fd, $AddrSeek);
        while(($char = fread($fd, 1)) != chr(0))
            $ipAddr1 .= $char;
    } else {
        fseek($fd, -1, SEEK_CUR);
        while(($char = fread($fd, 1)) != chr(0))
            $ipAddr1 .= $char;
        $ipFlag = fread($fd, 1);
        if($ipFlag == chr(2)) {
            $AddrSeek2 = fread($fd, 3);
            if(strlen($AddrSeek2)                 fclose($fd);
                return 'System Error';
            }
            $AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
            fseek($fd, $AddrSeek2);
        } else {
            fseek($fd, -1, SEEK_CUR);
        }
        while(($char = fread($fd, 1)) != chr(0)){
            $ipAddr2 .= $char;
        }
    }
    fclose($fd);
    //最后做相应的替换操作后返回结果
    if(preg_match('/http/i', $ipAddr2)) {
        $ipAddr2 = '';
    }
$ipaddr = "$ipAddr1 $ipAddr2";
$ipaddr = preg_replace('/CZ88.Net/is', '', $ipaddr);
$ipaddr = preg_replace('/^s* /is', '', $ipaddr);
$ipaddr = preg_replace('/s*$/is', '', $ipaddr);
if(preg_match('/http/i', $ ipaddr) || $ipaddr == '') {
$ipaddr = 'Unknown';
}
$ipaddr = iconv('gbk', 'utf-8//IGNORE', $ipaddr) ; //Convert encoding, if the gbk of the web page can delete this line
return $ipaddr;
}

2. Use the portal interface
Currently, it is known that Tencent, Sina, NetEase, Sohu and Google provide IP address query API, but the only ones that can be found are Tencent, Sina and NetEase. Google seems to use Google Maps, so there is no research. After looking at several domestic Tencent services, they provide JavaScript, NetEase provides XML, and Sina has a variety of formats available. Note that non-XML data sources are all in GBK format, regardless of whether they are JavaScript calls or PHP calls. You need to convert the encoding, otherwise you will get garbled codes. What needs more attention is that if you query multiple IPs at once, using the portal's API to query will be very slow. I probably wrote a for loop and tried it, whether using PHP to parse XML or the file_get_contents() function to obtain the content. , querying more than 10 times will become very slow and may even time out.

Tencent’s IP address API interface address: http://fw.qq.com/ipaddress, the returned data format is: var IPData = new Array("123.124.2.85","","Beijing City","");, a JavaScript object, it is not yet known how to enter an IP query.
Sina’s IP address query interface: http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js
Sina’s multi-region testing method: http://int.dpool. sina.com.cn/iplookup/iplookup.php?format=js&ip=123.124.2.85
NetEase Youdao’s IP address query interface: http://www.youdao.com/smartresult-xml/search.s?type =ip&q=123.124.2.85
//PHP calling method of Tencent API
Copy code Code As follows:

function getIpPlace(){
$ip=file_get_contents("http://fw.qq.com/ipaddress");
$ip=str_replace('"' ,' ',$ip);
$ip2=explode("(",$ip);
$a=substr($ip2[1],0,-2);
$b= explode(",",$a);
return $b;
}
$ip=getIpPlace();
print_r($ip);

//Youdao API PHP calling method
Copy code The code is as follows:

$url = "http:www.youdao.com/smartresult-xml/search.s?type=ip&q=".$ip;
$doc = new DOMDocument();
$doc-> load($url);
$smartresult = $doc->getElementsByTagName("product");
foreach($smartresult as $product)
{
$locations = $product-> getElementsByTagName("location");
$location = $locations->item(0)->nodeValue;
}
if($location != "")
{
echo $i.".".$ip;
echo " User from ".$location.";
}
else
{
echo $i.".". $ip;
echo "Netizens from Mars";
}
public function sinaIPApi($ip){
$str = file_get_contents("http://int.dpool.sina.com. cn/iplookup/iplookup.php?ip=".$ip);
$str = iconv("gbk", "utf-8//IGNORE", $str);
preg_match_all("/[/ x{4e00}-/x{9fa5}]+/u",$str,$get);
$add = implode('',$get[0]);
return $add;
}
//$get is a great two-dimensional array

Among them, Youdao and Sina are written by me. Sina API can also use the file_get_contents() function like Tencent API to obtain the address and then use a series of string functions to process it. The function I wrote uses regular expressions from Sina The return result provides a string containing Chinese characters and stores it in a two-dimensional array in segments. This may only be useful for Sina's API and may contain bugs. For example, after querying the IP address assigned to me by the school, var_dump() the $get variable in the function and get the following results: array(1) { [0]=> array(6) { [0]=> string( 6) "China" [1]=> string(6) "Beijing" [2]=> string(6) "Beijing" [3]=> string(9) "Education Network" [4]=> ; string(6) "school" [5]=> string(18) "China University of Geosciences" } }, and the output result of the function is "China University of Geosciences, Beijing Education Network School, Beijing, China". I hope my ideas are consistent with The method can be useful to others.

Finally, please use the first method if it is WordPress. Otherwise, using the API to query the real addresses of all commenters at the same time will cause PHP to time out. I hope that all the experts will have a better method. As for the restrictions, The display and display methods are all WordPress application issues. At the same time, the idea is the same for Java and C#. I will elaborate on these follow-up issues after I finish the exam.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327523.htmlTechArticleIf you want to convert the IPv4 address to a real address, you must refer to the IP database. The commercial IP database is stored in the relationship In a large database, querying and using are very convenient, but the cost is not personal and...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.