本文介绍了有兴趣制作将IP地址从定义的起始地址增加到定义的结束地址的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?

推荐答案

类似这样的内容:

Something like this:

<?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]++;
            }
        }
    }
}

?>

这篇关于有兴趣制作将IP地址从定义的起始地址增加到定义的结束地址的PHP脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:14