The first one liner I would write as the following:
# convert IP addresses to unsigned long integers my $addr="192.168.10.2"; my @addrb=split("[.]",$addr); my ( $addrval ) = unpack( "N", pack( "C4",@addrb ) ); my $mask="255.255.254.0"; my @maskb=split("[.]",$mask); my ( $maskval ) = unpack( "N", pack( "C4",@maskb ) ); # calculate network address my $netwval = ( $addrval & $maskval ); # convert network address to IP address my @netwb=unpack( "C4", pack( "N",$netwval ) ); my $netw=join(".",@netwb); # print print( $netw );
What I'm doing is converting the dot notation into an integer. That way I can do bit manipulation on the address as a whole rather than trying to deal with individual bytes.
To get the broadcast address should be just as easy. Although I haven't done bit inversions in Perl before..
# calculate broadcast address my $brodval = ( $addrval & $maskval ) + ( ~ $maskval );
So the whole file together looks like this:
# convert IP addresses to unsigned long integers my $addr="192.168.10.2"; my @addrb=split("[.]",$addr); my ( $addrval ) = unpack( "N", pack( "C4",@addrb ) ); my $mask="255.255.254.0"; my @maskb=split("[.]",$mask); my ( $maskval ) = unpack( "N", pack( "C4",@maskb ) ); # calculate network address my $netwval = ( $addrval & $maskval ); # calculate broadcast address my $brodval = ( $addrval & $maskval ) + ( ~ $maskval ); # convert network address to IP address my @netwb=unpack( "C4", pack( "N",$netwval ) ); my $netw=join(".",@netwb); # convert broadcast address to IP address my @brodb=unpack( "C4", pack( "N",$brodval ) ); my $brod=join(".",@brodb); # print print( "Network:$netw\n" ); print( "Broadcast:$brod\n" );
The output is:
Network:192.168.10.0 Broadcast:192.168.11.255
One lining this is left as an exercise for the reader.
Update: on a more personal note I would caution against the byte-at-a-time approach because of the possible error whereby the third byte should be different to what you expect for the broadcast address.. using the netmask supplied (255.255.254.0) both the 3rd and 4th bytes are affected, not just the 4th.
Update 2: Just making this more sexy, an alternative presentation of the code is as follows:
sub addrtoint { return( unpack( "N", pack( "C4", split( /[.]/,$_[0] ) +) ) ) }; sub inttoaddr { return( join( ".", unpack( "C4", pack( "N", $_[0] ) ) +) ) }; my $netwval = addrtoint( '192.168.10.2' ) & addrtoint( '255.255.254.0' + ); my $brodval = $netwval | ( ~addrtoint( '255.255.254.0' ) ); print( inttoaddr( $netwval ) . "\n" ); print( inttoaddr( $brodval ) . "\n" );
Update 3: Just letting everyone know I added readmore tags to update 2. I have to put in lots of update notices cause I was told off by a Saint yesterday for not putting update notices in every single time I make an update, no matter how small, and no matter how frequently.
In reply to Re: perl ipcalc oneliners
by monarch
in thread perl ipcalc oneliners
by mojobo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |