Simple perl ipcalc

Here is a simple program to calculate Network address and broadcast address, given input of IP address and netmask.

Perl code :


# Get ipaddress and netmask from user

my $ipaddr=$ARGV[0];
my $nmask=$ARGV[1];

my @addrarr=split(/./,$ipaddr);
my ( $ipaddress ) = unpack( “N”, pack( “C4”,@addrarr ) );

my @maskarr=split(/./,$nmask);
my ( $netmask ) = unpack( “N”, pack( “C4”,@maskarr ) );

# Calculate network address by logical AND operation of addr & netmask
# and convert network address to IP address format
my $netadd = ( $ipaddress & $netmask );
my @netarr=unpack( “C4”, pack( “N”,$netadd ) );
my $netaddress=join(“.”,@netarr);

print “Network address : $netaddress n”;

# Calculate broadcase address by inverting the netmask
# and do a logical or with network address
my $bcast = ( $ipaddress & $netmask ) + ( ~ $netmask );
my @bcastarr=unpack( “C4”, pack( “N”,$bcast ) ) ;
my $broadcast=join(“.”,@bcastarr);

print “Broadcast address: $broadcastn”;

# END of program

Here is the output of it.

[[email protected] tmp]# ./
Network address :
Broadcast address:
[[email protected]unixfoo tmp]#

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

Linux modules handling commands

Next Post

Kernel parameter : file-nr and file-max

Related Posts