开发者

generating and using all IP addresses with php

knowing nothing about java (I 开发者_StackOverflow社区thought a thread on this same topic for java) and a tiny bit about php, I was wondering how I could generate, with php, a complete list of all the possible IPs (0.0.0.0 to 255.255.255.255) and then how I can use each of those in a php script that is intended to test a IP verification tool that I am trying to set up (take each one of them and use it).

For the second part of the question, I was thinking about using a foreach statement or using the part of the "testing code" inside the loop that would generate each IP combination, so that it is tested as the IPs are generated.

Then for the first part, I have to admit that I am stuck and that my basic knowledge doesn't enable me to find a satisfying solution So far I have come with this:

function gen() {
    $n1 = 0;
    $n2 = 0;
    $n3 = 0;
    $n4 = 0;

    while ($n4 <= 255 && $n3 <= 255) {
        echo $n1.'.'.$n2.'.'.$n3.'.'.$n4++.'<br>';
        echo $n1.'.'.$n2.'.'.$n3++.'.'.$n4.'<br>';
    }
}
gen();

which just partially does what I want.


Rather than generating a possible database / storage for ~4 billion IP4 addresses (assuming you are only looking at IPv4 ignoring all IPv6 addresses) would it not be easier, and more practical just generate random IP address combinations to test with, which you can easily validate with RegEx?

The following regex would allow you to validate any particular IPv4 address from 0.0.0.0 to 255.255.255.255

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

What you do need to remember however is that not all combinations of addresses are classed as 'valid' even if they are syntax correct.

Another alternative (as also mentioned by @binaryLV) is using the PHP filter_var($ip, FILTER_VALIDATE_IP); function which is nice and clean. Check the flags out to help filter too over at http://php.net/manual/en/function.filter-var.php

Update

For IP location based services I would recommend using a service such as IPInfoDB. They provide both an API (see here) to use which allows you to call their service reducing the need to store the information on your database. Else they offer a database of IP addresses (see here) to xxx.xxx.xxx precision that can also be downloaded.


You need nested loops:

for($n1=0; $n1 < 256; $n1++) {
    for($n2=0; $n2 < 256; $n2++) {
        for($n3=0; $n3 < 256; $n3++) {
            for($n4=0; $n4 < 256; $n4++) {
                echo $n1 . "." . $n2 . "." . $n3 . "." . $n4 . "\n";
            }
        }       
    }
}   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜