简体   繁体   中英

how to check if a php variable containing an ip address, lies in the range of two ip addresses in inet_aton format

Query picture I have a table called blacklisted, having columns start_ip & end_ip, i need to check if my variable $stat_ip(another column from a table called Hasoffers) lies between the range ie is greater than or equal to start_ip and less than or equal to last_ip, using a mysql query. My query goes like this $result=mysql_query("Select inet_aton(network_start_ip),inet_aton(network_last_ip) from blacklisted where '".$stat_ip."' BETWEEN inet_aton(network_start_ip) AND inet_aton(network_last_ip)"). This does returns a 0 count, which is not the expected output. Help on mysql query is appreciated.

<?php
include('adodb/adodb.inc.php');
$link=mysql_connect("166.26.18.122","vcc","abcd1234");
mysql_select_db("vcc");
$pl=mysql_query("SELECT stat_ip fromHasoffers");
$count=mysql_num_rows($pl);

while($row=mysql_fetch_array($pl))
{
$stat_ip=$row['stat_ip'];
echo ip($stat_ip)."<br>";
$ip_Num=ip2long($stat_ip);
}

function blacklisted($ip_Num)
{
    $result=mysql_query("Select inet_aton(network_start_ip),inet_aton(network_last_ip) from blacklisted where '".$ip_Num."' BETWEEN  inet_aton(network_start_ip) AND inet_aton(network_last_ip)");
    $count=mysql_num_rows($result);


  return $count;

}
?>

you need to do inet_aton on your from Hasoffers query. like this

$pl=mysql_query("SELECT inet_aton(stat_ip) from Hasoffers");
$count=mysql_num_rows($pl);

without doing inet_aton $stat_ip has value with dots. eg 192.168.0.1

so your second query is like

Select inet_aton(network_start_ip),inet_aton(network_last_ip) from blacklisted where '192.168.0.1' BETWEEN  inet_aton(network_start_ip) AND inet_aton(network_last_ip)

In short change the first query and hopefully it will fix your problem.

UPDATE

As you said you can't change your query. try this

$pl=mysql_query("SELECT stat_ip from Hasoffers");    
while($row=mysql_fetch_array($pl))
{
$stat_ip=$row['stat_ip'];
echo ip($stat_ip)."<br>";
//for converting to LongInt
$ip_Num=ip2long($stat_ip);

} 
// Now pass $ip_Num instead of $stat_ip in your function 
function blacklisted($ip_Num)

you can ip2long(ipaddress) function insted of below line

        **$ip_Num=str_replace('.','',$stat_ip);**

ip2long is working line inet_aton() mysql function. ip2long is a php function eg:

$ip = '10.0.5.9'; printf("%u\\n", ip2long($ip));

167773449

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM