How to create valid IP ranges given the IP address and subnet mask in Perl?

How to create valid IP ranges given the IP address and subnet mask in Perl? I understand the concept of creating IP ranges, but I need help writing Perl. For example, if I AND the IP address and subnet mask, I get the subnet number. Adding 1 to this number should give me the first valid IP address. If I invert the subnet mask and OR with the subnet number, I should get the broadcast address. Subtracting 1 from it should contain the last valid IP address.

+3
source share
4 answers

See perldoc perlop for information on bitwise operators (they are the same as in most other C-like languages):

  • & bitwise AND
  • | bitwise OR
  • ^ bitwise xor
  • >> is a shift to the right
  • << - left shift

However, if you really want to do some work with network blocks and IP addresses (as opposed to just answering your homework), although I'm curious what course you will use using Perl), you can avoid reusing the wheel by turning to CPAN:

+3
source

If you want to play with bitwise operators yourself, it becomes the following:

#!/usr/bin/perl
use strict;
use warnings;
use Socket;

my $ip_address = '192.168.0.15';
my $netmask = 28;

my $ip_address_binary = inet_aton( $ip_address );
my $netmask_binary    = ~pack("N", (2**(32-$netmask))-1);

my $network_address    = inet_ntoa( $ip_address_binary & $netmask_binary );
my $first_valid        = inet_ntoa( pack( 'N', unpack('N', $ip_address_binary & $netmask_binary ) + 1 ));
my $last_valid         = inet_ntoa( pack( 'N', unpack('N', $ip_address_binary | ~$netmask_binary ) - 1 ));
my $broadcast_address  = inet_ntoa( $ip_address_binary | ~$netmask_binary );

print $network_address, "\n";
print $first_valid, "\n";
print $last_valid, "\n";
print $broadcast_address, "\n";

exit;

With Net :: Netmask, this is easier to understand:

#!/usr/bin/perl
use strict;
use warnings;
use Net::Netmask;

my $ip_address = '192.168.0.15';
my $netmask = 28;

my $block = Net::Netmask->new( "$ip_address/$netmask" );

my $network_address    = $block->base();
my $first_valid        = $block->nth(1);
my $last_valid         = $block->nth( $block->size - 2 );
my $broadcast_address  = $block->broadcast();

print $network_address, "\n";
print $first_valid, "\n";
print $last_valid, "\n";
print $broadcast_address, "\n";

exit;
+3
source

:

use Socket;
my $subnet_mask = inet_ntoa(inet_aton($ip_str) & inet_aton($mask_str)):
0

IP- rhel7

my $ip=`hostname -i`;
my $subnet = `ip addr show|grep -i ".*${ip}/.*"|tail -1|cut -d "/" -f2|cut -d " " -f1`;
0

Source: https://habr.com/ru/post/1722929/


All Articles