Skip to content

Instantly share code, notes, and snippets.

@Stevie-O
Created July 2, 2021 17:11
Show Gist options
  • Save Stevie-O/a54b26dd553318ff69274931caa9aa21 to your computer and use it in GitHub Desktop.
Save Stevie-O/a54b26dd553318ff69274931caa9aa21 to your computer and use it in GitHub Desktop.
Perl script for getting the broadcast address from an IP address and netmask
#!/usr/bin/perl -s
our $v;
use Socket qw/inet_ntoa inet_aton/;
if (@ARGV[0] =~ s#(/\d+)$##) { $ARGV[1] = $1; }
@ARGV >= 2 or die "Usage: perl $0 <address> <netmask>\n
netmask may be of the form '255.255.255.0' or '/24'
";
my $addr = inet_aton($ARGV[0]) // die "Unable to parse as IP address: $ARGV[0]";
my $netmask;
if ($ARGV[1] =~ m#/(\d+)$#) {
my $nbits = $1;
if ($nbits < 1 || $nbits > 32) { die "Invalid CIDR size $nbits (must be 1-32)"; }
$netmask = pack 'N', 0xFFFFFFFF ^ ((1 << (32-$nbits))-1);
print STDERR "netmask: ", inet_ntoa($netmask), "\n" if $v;
} else {
$netmask = inet_aton($ARGV[1]) // die "Unable to parse as IP address; $ARGV[1]";
}
my $all_ones = "\xFF" x 4;
$zero_addr = $addr & $netmask;
$bc_addr = $zero_addr | ($netmask ^ $all_ones);
print "broadcast address = " if $v;
print inet_ntoa($bc_addr), "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment