How can I go through a range of IP addresses?

I want to perform a set of network tasks in a range of IP addresses. Once the range becomes larger than the class c network, I cannot list all the hosts in the range. I want to be able to iterate through all network nodes using a netmask 255.255.240.0.

From: 192.168.0.100
To: 192.168.10.100

How to approach this? This should be a fairly common task. I came from the green Cocoa iPhone programming fields, so a C-stylish solution would be appreciated. :-)

+3
source share
3 answers

Use the module operator %. Here is an example:

#include <stdio.h>

int main(void) {
    int counter;
    unsigned int ip[] = { 192, 168, 0, 0 };

    for ( counter = 0; counter < 1000; ++counter ) {
        ip[3] = ( ++ ip[3] % 256 );
        if ( !ip[3] ) {
            ip[2] = ( ++ ip[2] % 256 );
        }
        printf("%u:%u:%u:%u\n", ip[0], ip[1], ip[2], ip[3]);
    }

    return 0;
}
+1
source

, , IP- .

, IP- 32- .

#include <stdio.h>
int
main (int argc, char *argv[])
{
    unsigned int iterator;
    int ipStart[]={192,168,0,100};
    int ipEnd[] = {192,168,10,100};

    unsigned int startIP= (
        ipStart[0] << 24 |
        ipStart[1] << 16 |
        ipStart[2] << 8 |
        ipStart[3]);
    unsigned int endIP= (
        ipEnd[0] << 24 |
        ipEnd[1] << 16 |
        ipEnd[2] << 8 |
        ipEnd[3]);

    for (iterator=startIP; iterator < endIP; iterator++)
    {
        printf (" %d.%d.%d.%d\n",
            (iterator & 0xFF000000)>>24,
            (iterator & 0x00FF0000)>>16,
            (iterator & 0x0000FF00)>>8,
            (iterator & 0x000000FF)
        );
    }

    return 0;
}

, ipStart ipEnd 255.
IP-, .

+7

PHP-:

<?php

$sIP1 = '192.168.0.0';
$sIP2 = '192.168.1.255';

$aIPList = array();
if ((ip2long($sIP1) !== -1) && (ip2long($sIP2) !== -1)) // As of PHP5, -1 => False
 {
 for ($lIP = ip2long($sIP1) ; $lIP <= ip2long($sIP2) ; $lIP++)
  {
  $aIPList[] = long2ip($lIP);
  }
 }
?>

()

+1

Source: https://habr.com/ru/post/1711037/


All Articles