首页 > 解决方案 > 如何在 PHP 中获取 IP 列表的完整 IP 范围

问题描述

我有一些在文本文件 ips.txt 中。我想从该列表中获取每个 IP 的完整 IP 范围。

   The following is included in ips.txt
    37.123.206.198
    115.84.182.49
    154.16.116.35
    115.84.182.49
    142.250.192.14
    112.78.2.75

如何获得每个 ip 的完整 IP 范围?1-255

Example (with first IP)
37.123.206.198

37.123.1.1
37.123.2.1
37.123.3.1
37.123.4.1
.
.
.
37.123.255.1
37.123.1.2
37.123.2.2
37.123.3.2
37.123.4.2

标签: phpip-address

解决方案


读取文件并将 ips 存储在数组中。然后:

<?php
$ips = [
    "37.123.206.198",
    "115.84.182.49",
    "154.16.116.35",
    "115.84.182.49",
    "142.250.192.14",
    "112.78.2.75"
];

$result = [];

foreach ($ips as $ip) {
    $ip_arr = explode('.', $ip);
    for ($i = 0; $i <= 255; $i++) {
        for ($j = 0; $j <= 255; $j++) {
            $new_ip = $ip_arr[0] . '.' . $ip_arr[1] . '.' . $i . '.' . $j;
            $result[$ip][] .= $new_ip;
        }
    }
}

print_r($result["37.123.206.198"][0]);


?>

输出:37.123.0.0


推荐阅读