PHP checks if IPAddress is local

Can I check if ip is on a private network?

<?php
function isLocalIPAddress($IPAddress)
{
    return ( !filter_var($IPAddress, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) );
}

var_dump( isLocalIPAddress('127.0.0.1') ); // false
var_dump( isLocalIPAddress('192.168.1.20') ); // true
var_dump( isLocalIPAddress('64.233.160.0') ); // false

Why isLocalIPAddress('127.0.0.1')gives falseinstead true?

Is 127.0.0.1 a private ip?


UPDATE

The solution I used:

<?php
function isLocalIPAddress($IPAddress)
{
    if( strpos($IPAddress, '127.0.') === 0 )
        return true;

    return ( !filter_var($IPAddress, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) );
}
+4
source share
3 answers

According to the test run , we can see that the output is for PHP 5.2.0 → 5.3.5 - false, and the output for PHP 5.3.6 → 7.0.0beta1 and hhvm-3.3.1 → 3.8.0 - true.

To solve your problem you can check the php version and if it is in the first range add:

function isLocalIPAddress($IPAddress)
{
    if($IPAddress == '127.0.0.1'){return true;} <-- add this
    return ( !filter_var($IPAddress, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) );
}
+5
source
filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);

. IP- loopback .

+2

http://www.php.net/manual/en/filter.filters.flags.php 127.0.0.1 FILTER_FLAG_NO_PRIV_RANGE, FILTER_FLAG_NO_RES_RANGE.

:

There is also a comment on how to deal with loopback.

0
source

Source: https://habr.com/ru/post/1543246/


All Articles