Determine whether the user ip address is in the same CIDR block or on the same LAN instance-PHP source code

Source: Internet
Author: User
The principle is to obtain the current ip address based on the IP Address Provided by the user and convert it to a digital IP address. The calculation is based on the ip address, a, B, and c, according to the comparison, the "OK" principle is based on the ip address given by the user, and then the current IP address is obtained and converted to a numeric type. The calculation is based on the IP address, a, B, and c.

Script ec (2); script

The Code is as follows:
$ Start = ipToInt ('192. 168.1.110 ');
$ End = ipToInt ('192. 168.0.1 ');
$ IpInt = ipToInt (get ());
$ Result = false;
If ($ ipInt >=$ start & $ ipInt <= $ end ){
$ Result = true;
}

If ($ result)
{
Echo 'in the same CIDR Block ';
}
Else
{
Echo 'not in the same CIDR Block ';
}


// Not in the same CIDR Block

/*
* Convert an IP address to an integer value.
* @ Param string $ ip Address
* @ Return int
*/

The Code is as follows:
Function ipToInt ($ ip ){
$ Ips tutorial = explode ('.', $ ip );
If (count ($ ips)> = 4 ){
$ Int = $ ips [0] * 256*256*256 + $ ips [1] * 256*256 + $ ips [2] * 256 + $ ips [3]; // calculate based on IP, a, B, and c
} Else {
Throw new Exception ('IP is error ');
}
Return $ int;
}


/*
* Obtain the user IP address 192.68.0.110
*/

The Code is as follows:
Function get (){
If ($ _ SERVER ['HTTP _ CLIENT_IP '] & $ _ SERVER ['HTTP _ CLIENT_IP']! = 'Unknown '){
$ Ip = $ _ SERVER ['HTTP _ CLIENT_IP '];
} Elseif ($ _ SERVER ['HTTP _ X_FORWARDED_FOR '] & $ _ SERVER ['HTTP _ X_FORWARDED_FOR']! = 'Unknown '){
$ Ip = $ _ SERVER ['HTTP _ X_FORWARDED_FOR '];
} Else {
$ Ip = $ _ SERVER ['remote _ ADDR '];
}
Return $ ip;
}
/*

Original site reprinted with the source www.111cn.net
*/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.