如何比较两个PhP变量中包含的两个Ip地址的前三个八位字节

时间:2017-02-28 10:05:01

标签: php

我有两个php变量,其中包含两个ipv4地址,我需要比较前三个八位字节,如果匹配则返回true,如果不匹配则返回false。感谢编写代码块的帮助。

<?php
include('adodb/adodb.inc.php');
mysql_connect("173.86.45,9","abcd","1236");
mysql_select_db("vc");
$pl=mysql_query("SELECT stat_ip from Hasoffers");
$count=mysql_num_rows($pl);


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

function sec($stat_ip)
{
  $result = mysql_query("select stat_ip from Hasoffers where stat_ip ='".$stat_ip."'");



                  if(condition to check if the octets match)
                {
                  //i need to write the condition if within the table Hasoffers, there are more than 2 'stat_ip'(column) values, having the same 3 octets.
                   printf("true");

                   }

               else
              {
                printf("false, octets don't match");


              }
                 return $num_rows;
}



?>

4 个答案:

答案 0 :(得分:2)

实现这个的简单方法是:

$ip1 = '192.168.0.1';
$ip2 = '192.168.0.2';

$ip1 = explode('.', $ip1);
$ip2 = explode('.', $ip2);
if ($ip1[0]==$ip2[0] && $ip1[1]==$ip2[1] && $ip1[2]==$ip2[2]) {
    //your code here
}

编辑: 尝试用这个替换你的sec()函数(阅读注释),然后编辑它。

function sec($stat_ip)
{
$octets = explode('.', $stat_ip);
$first_three = $octets[0].'.'.$octets[1].'.'.$octets[2].'.'; //this looks like 192.168.0.
  $result = mysql_query("SELECT stat_ip from Hasoffers where stat_ip LIKE '".$first_three."%'"); //this gives you all ip's starting with the current ip
  if (mysql_num_rows($result)>1) 
  {
    //we have more than one ip starting with current ip
    //do something here
  }
  else
  {
    //result returns 1 or 0 rows, no matching ip's
  }
   //return $something;
}

答案 1 :(得分:2)

使用strrpossubstr函数的解决方案:

$ip1 = '192.168.10.121';
$ip2 = '192.168.10.122';

// the position of the last octet separator
$last_dot_pos = strrpos($ip1, '.');
$is_matched = substr($ip1, 0, $last_dot_pos) == substr($ip2, 0, $last_dot_pos);

var_dump($is_matched);

输出:

bool(true)

答案 2 :(得分:1)

使用此代码:

    $ipOne = "192.168.1.1";
    $ipTwo = "192.168.1.2";

    $ipOneParts = explode(".", $ipOne);
    $ipTwoParts = explode(".", $ipTwo);

    if(($ipOneParts[0] == $ipTwoParts[0]) && 
       ($ipOneParts[1] == $ipTwoParts[1]) && 
       ($ipOneParts[2] == $ipTwoParts[2])){
        return true;
    } else {
        return false;
    }

答案 3 :(得分:0)

使用&#34;使用爆炸将它们转换为数组。&#34;并比较两个数组的第一个索引。