Home Backend Development PHP Tutorial PHP实现IP数字互相转换

PHP实现IP数字互相转换

Jun 23, 2016 pm 01:26 PM
php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP中文网</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
</head>
<body>
<?php
/*
* 作者:XXXX
*/
//将IP转换为数字
function ipton($ip)
{
    $ip_arr=explode(&#39;.&#39;,$ip);//分隔ip段
    foreach ($ip_arr as $value)
    {
        $iphex=dechex($value);//将每段ip转换成16进制
        if(strlen($iphex)<2)//255的16进制表示是ff,所以每段ip的16进制长度不会超过2
        {
            $iphex=&#39;0&#39;.$iphex;//如果转换后的16进制数长度小于2,在其前面加一个0
        //没有长度为2,且第一位是0的16进制表示,这是为了在将数字转换成ip时,好处理
        }
        $ipstr.=$iphex;//将四段IP的16进制数连接起来,得到一个16进制字符串,长度为8
    }
    return hexdec($ipstr);//将16进制字符串转换成10进制,得到ip的数字表示
}
 
 
//将数字转换为IP,进行上面函数的逆向过程
function ntoip($n)
{
    $iphex=dechex($n);//将10进制数字转换成16进制
    $len=strlen($iphex);//得到16进制字符串的长度
    if(strlen($iphex)<8)
    {
        $iphex=&#39;0&#39;.$iphex;//如果长度小于8,在最前面加0
        $len=strlen($iphex); //重新得到16进制字符串的长度
    }
    //这是因为ipton函数得到的16进制字符串,如果第一位为0,在转换成数字后,是不会显示的
    //所以,如果长度小于8,肯定要把第一位的0加上去
    //为什么一定是第一位的0呢,因为在ipton函数中,后面各段加的&#39;0&#39;都在中间,转换成数字后,不会消失
    for($i=0,$j=0;$j<$len;$i=$i+1,$j=$j+2)
    {//循环截取16进制字符串,每次截取2个长度
        $ippart=substr($iphex,$j,2);//得到每段IP所对应的16进制数
        $fipart=substr($ippart,0,1);//截取16进制数的第一位
        if($fipart==&#39;0&#39;)
        {//如果第一位为0,说明原数只有1位
            $ippart=substr($ippart,1,1);//将0截取掉
        }
        $ip[]=hexdec($ippart);//将每段16进制数转换成对应的10进制数,即IP各段的值
    }
    $ip = array_reverse($ip);
     
    return implode(&#39;.&#39;, $ip);//连接各段,返回原IP值
}
echo ipton(&#39;119.255.31.226&#39;);
echo &#39;<br>&#39;;
$num=&#39;379374783&#39;;
echo strlen($num).&#39;<br/>&#39;;
echo ntoip($num).&#39;<br/>&#39;;
 
 
echo &#39;trueipnum:&#39;.ip2long(&#39;119.255.31.226&#39;).&#39;<br/>&#39;;
echo &#39;trueip:&#39;.long2ip(&#39;3793747831&#39;);
?>
</body>
</html>
Copy after login

mysql自带了inet_aton函数来实现将ip地址转换为数字,inet_ntoa函数将数字转换为ip。

SELECT INET_ATON( '10.122.22.1' )

上面的转换函数为站长原创,碰巧实现了跟mysql系统函数相同的转换效果,呵呵,兴奋好久~~
原来PHP提供了ip2long和long2ip2个函数来实现IP与数字的转换,站长做了无用功了,不过权当锻炼逻辑思维吧~~
这是两种实现方法,一种是在程序上实现;一种是直接在sql语句中实现,很方便,不错,保存下来了,发到自己的博客,以后就不会忘记了。


把ip数据保存在数据库(MySQL)中时候,我们习惯用ip2long函数生成整型,然后存放在一个int(11)类型的字段中,但是,在不同的系统平台上,ip2long函数得到的值是不同的,因此可能造成在从数据库中读出数据,用long2ip得到ip的时候产生错误,说一下我们碰到的情况:
我们用一个int(11)类型(范围-2147483648 - 2147483647)来保存把一个ip地址用ip2long处理得到的结果,例如ip是’202.105.77.179′,那么在32位机器上得到的结果是:-899068493,而在64位机器上却得到3395898803.然后把它写入数据库,由于超过int(11)的范围,因此64位机器上的结果被保存为int(11)的最大值:2147483647.于是在从数据库中取出的时候,便得到了错误的结果,会得到”127.255.255.255″这个ip地址.
解决的办法很多,比如可以用mysql的函数:INET_ATON和INET_NTOA来处理ip地址;或者把保存ip地址的字段改为bigint类型,这样在64位机器上虽然保存的是3395898803,使用long2ip函数仍能得到正确的结果.


Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles