in reply to Increment of ip address

Net::IP or NetAddr::IP is really the way to go... but for fun, here's a simple IP math function. (Note that it only works on IPv4 addresses.)
use Socket; sub add_to_ip($$) { my( $ip, $add ) = @_; inet_ntoa pack( 'N', unpack('N',inet_aton $ip) + $add ) }
You can add or subtract any amount to an IP address this way. Carry-over into the next "quad" is automatic... but that may not be what you want. :-)
$j = add_to_ip( $i, 1 ); # simple increment $j = add_to_ip( $i, -1 ); # simple decrement $j = add_to_ip( $i, 300 ); # addition carries over into the next-to-la +st quad.

Replies are listed 'Best First'.
Re^2: Increment of ip address
by mosh (Scribe) on Jun 16, 2005 at 18:13 UTC
    Hi jdporter, Thanks !

    What does it mean the $$ in:
    sub add_to_ip($$)

    Mosh.

      That would be a prototype, the subject of much discussion on usefulness verging on holy war status.  The Camel Book says the intent behind prototypes "... is primarily to let you define subroutines that work like built-in functions ..." (p. 226).  In this case, it is giving a contextual clue to perl that this sub accepts two scalars.