Simple perl ipcalc

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

Perl code :

#!/usr/bin/perl

# 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]# ./ipcalc.pl 139.18.16.119 255.255.254.0
Network address : 139.18.16.0
Broadcast address: 139.18.17.255
[[email protected]unixfoo tmp]#

Total
0
Shares
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