有兴趣制作一个 PHP 脚本,将 IP 地址从定义的起始地址增加到定义的结束地址

2022-01-24 00:00:00 ip-address range php

我知道我可以通过首先使用 PHP 内置函数(如 up2longlong2ip)将 IP 地址转换为十进制表示法轻松做到这一点.我只是希望能够使用标准 IP 地址表示法做同样的练习.

I know I can do this easily by converting the IP addresses to decimal notation first using PHP built in functions like up2long and long2ip. I just want to be able to do the same using the standard IP address notation as an exercise.

我想的问题是这样的:给定一个起始 IP 地址,比如 192.168.1.100,和一个结束 IP 地址,比如 201.130.22.10.制作打印该范围内所有地址编号的程序(192.168.1.100、192.168.1.101、...、201.130.22.9、201.130.22.10).

The problem I am thinking goes like this: Given an starting IP address, say 192.168.1.100, and an ending IP address, say 201.130.22.10. Make the program that prints all the address numbers in that range (192.168.1.100, 192.168.1.101, … , 201.130.22.9, 201.130.22.10).

我在想,也许要走的路是在 while 条件内创建一个嵌套的 for 循环,直到起始地址的第一个八位字节与第一个八位字节匹配的结束地址.然后对第二个八位字节执行相同的代码块,依此类推,直到程序到达结束地址并完成.

I was thinking that maybe the way to go would be to make a nested for loop inside a while condition until the first octet of the starting address matches the first octet of the ending address. Then execute the same block of code for the second octet and so on until the program reaches the ending address and finished.

我最近才开始学习编程,所以我的思考和/编写代码很可能远非优雅.如果你要这样做,你会怎么做?

I just started learning to program recently so it is quite possible that my of thinking and or writing code is far from elegant. If you were to this, how would you do it?

推荐答案

类似这样的:

<?php

// works only for valid range
$start_ip = '10.0.0.1';
$end_ip = '10.0.20.1';

$start_arr = explode('.',$start_ip);
$end_arr = explode('.',$end_ip);

while($start_arr <= $end_arr)
{
    echo implode('.',$start_arr) . '<br>';

    $start_arr[3]++;
    if($start_arr[3] == 256)
    {
        $start_arr[3] = 0;
        $start_arr[2]++;
        if($start_arr[2] == 256)
        {
            $start_arr[2] = 0;
            $start_arr[1]++;
            if($start_arr[1] == 256)
            {
                $start_arr[1] = 0;
                $start_arr[0]++;
            }
        }
    }
}

?>

相关文章