我有一个存储IP地址的数据库表,如下所示:
E_ID IP MASK
我想让它看起来像这样:
E_ID Parent_ID IP MASK
这样我可以很容易地得到我的IP地址树:
80.17.0.0/18 (id=1 parent id = -1)
80.17.0.0/24 (id=2, parent id=1)
80.17.0.0/27 (id=3, parent id=2)
80.17.0.0/31 (id=4, parent id=3)
80.17.0.2/31 (id=5, parent id=3)
80.17.0.4/31 (id=6, parent id=3)
80.17.0.6/31 (id=7, parent id=3)
80.17.0.8/31 (id=8, parent id=3)
80.17.0.12/31 (id=9, parent id=3)
80.17.0.32/27 (id=10, parent id=2)
80.17.0.32/30 (id=11, parent id=10)
80.17.0.32/32 (id=12, parent id=11)
80.17.0.33/32 (id=13, parent id=11)
80.17.0.34/32 (id=14, parent id=11)
80.17.0.35/32 (id=15, parent id=11)
所有ip和mask都是BINGINT (ip2long())。我想到的是:
$sql = "SELECT IP, Mask, E_ID
FROM test
ORDER BY `IP`, `Mask` ASC";
$result = mysqli_query($db, $sql) or die(mysqli_error($db));
$space = array();
$i = 0;
array_push($space, mysqli_fetch_assoc($result));
while($r = mysqli_fetch_assoc($result)){
if(!ipvsnet(long2ip($r['IP']), long2ip($space[$i]['IP']), long2ip($space[$i]['Mask']))){
array_push($space, $r);
$i++;
}
function ipvsnet($ip, $network, $mask){
if(((ip2long($ip))&(ip2long($mask))) == ip2long($network)){
return 1;
} else {
return 0;
}
}
这只给了我主父地址。我不知道如何找到更深的节点,因为我不知道每个分支有多深。
从外观上看,您正在尝试按网络id,然后子网掩码,然后节点id排序/组织您的IP地址。我认为你误解了子网掩码在IP寻址中的作用(这是一个非常常见的错误,我也曾经犯过这个错误:))。
子网掩码用于分隔网络id和IP地址。子网掩码是一个二进制数,由从二进制字(4字节二进制值)的最高有效位开始的不间断的1位序列组成。例如:
11110000.00000000.00000000.00000000 // subnet_mask: /4
11111000.00000000.00000000.00000000 // subnet_mask: /5
11011000.00000000.00000000.00000000 // not a legal bitmask because of the 0 bit
当你考虑一个随机的IP地址,比如74.125.224.197(这里要做一点数学运算),我们得到位模式:
01001010.01111101.11100000.11000101 // This is the same as 74.125.224.197
现在如果我们有这个特定IP的子网掩码例如:
11110000.00000000.00000000.00000000
那么网络id将是子网掩码和IP地址的逻辑与:
01001010.01111101.11100000.11000101 // ip
& 11110000.00000000.00000000.00000000 // subnet mask
---------------------------------------
01000000.00000000.00000000.00000000 // Network Id
沿着逻辑上类似的路线,节点id将是IP地址的逻辑与和子网掩码的/否定/:
/* negation of subnet mask via XOR */
11110000.00000000.00000000.00000000 // subnet mask
XOR 11111111.11111111.11111111.11111111
---------------------------------------
00001111.11111111.11111111.11111111 // negation of subnet mask
/* getting the node id from the IP address using the negation of subnet mask */
00001111.11111111.11111111.11111111 // negation of subnet mask
& 01001010.01111101.11100000.11000101 // original IP address
---------------------------------------
00001010.01111101.11100000.11000101 // the node Id
所有这一切的重点是建立一个矛盾,你对子网掩码的性质的理解,因此你的排序顺序。考虑这样一个子网掩码:
01001010.01111101.11100000.11000101 // original IP address of google
& 11000000.00000000.00000000.00000000 // different subnet mask
---------------------------------------
01000000.00000000.00000000.00000000 // same network id(sort of) as above
我们如何区分这次生成的结果和上次计算网络id时的结果?答案与子网掩码有关。子网掩码实际上是用来确定网络id的。IP地址和子网掩码应该一起考虑,因为您需要两者来确定网络id(这看起来像是您正在尝试订购的)。
如果你想组织你的数据进行有意义的操作,首先考虑将原始IP地址+子网掩码转换成适当的网络id和节点id部分。剩下的事情很快就会摆平。
我真的希望这有助于男人!