perl : find if IP address is in Network range

Using NetAddr::IP one can find if a given IP address is in provided Network range or on the subnet. This can take many different representations of the subnet address. For example you can throw at it the CIDR (e.g. 192.168.1.0/29) or explicit start and end addresses (e.g. 192.168.1.0-192.168.1.7) or even with network mask (e.g. 192.168.1.0 mask 255.255.255.248). Following example shows all of these possible cases.

#!/usr/local/bin/perl

use NetAddr::IP;

my $ipAddr  = "192.168.1.8";
my $netAddr = "192.168.1.0/29"; # 192.168.1.0 - 192.168.1.7

my $network  = NetAddr::IP->new($netAddr);
#my $network  = NetAddr::IP->new("192.168.1.0", "255.255.255.248");
#my $network  = NetAddr::IP->new("192.168.1.0", "29");
#my $network  = NetAddr::IP->new("192.168.1.0-192.168.1.7");
my $ip = NetAddr::IP->new($ipAddr);

if ($ip->within($network)) {
        print $ip->addr() . " is in same subnetn";
}
else {
        print $ip->addr() . " is outside the subnetn";
}

There are multiple ways the input for network can be provided (four ways are shown above with 3 commented).

perl : Process Command Line Arguments

GetOpt module in perl provides a very easy way to process the command line arguments. It also performs the type check. Here is a sample snippet that I use very often.

use Getopt::Long;

#Process command line arguments
$result = GetOptions(
	"port=i"	=> $Port,
	"host=s"	=> $Host,
	"interval=f"	=> $Interval,
	"random!"	=> $Randomize,
	"h"		=> $Help
);

The type after the equal “=” sign dictates the type of variable that is expected. This is very helpful because the module will perform the type checking and ensure that it receives what is expected. For example if you try to give –port “abcd” it will fail that an integer is expected. Read on for a brief explanation of types. Continue reading

perl : Generate Random Data Natively

If you have the luxury to use Data::Random then use that by all means. But if that is not available (for example in production environment), here is another way to create some random data.

sub generate_random_data
{
	my $passwordsize = shift;
	my @alphanumeric = ('a'..'z', 'A'..'Z', 0..9);
	my $randpassword = join '',
	map $alphanumeric[rand @alphanumeric], 0..$passwordsize;

	return $randpassword;
}

perl : Extract filename from full path

To extract the name of the file the quick way is to use substr and rindex commands to strip the path from filename as shown below.

#!/usr/bin/perl

my $path='/path/to/search/filename';
my $fname= substr($path, rindex($path,"/")+1, length($path)-rindex($path,"/")-1);
print "$fnamen";

If you have the luxury of using Perl Packages, then use following solution which is very clean.

#!/usr/bin/perl

use File::Basename;
my $path='/path/to/search/filename';
my $fname = basename($path);
print "$fnamen";

perl : Read filenames from a Directory

Perl provides built in glob function which can be used to read the list of files in a directory.

@files = </path/to/search/pattern_to_search>;

Here is working code example that prints all filenames from current directory, one per line. The glob happens when the <> characters pulls the filenames into the @files array.

#!/usr/bin/perl
@files = <*>;
foreach $file (@files) {
        print "$filen";
}

So if you were to find all php files in your webserver directory use

@files = </var/www/htdocs/*.php>

perl : Set different TimeZone for script

Here is how to set the timezone inside a perl script. A use case is when the application is communicating with some server in a different timezone and you want to log the time in the timezone of the other end instead of the timezone where this script is running.

$ENV{TZ} = ':/usr/share/zoneinfo/US/Eastern';

perl : Create unix time from readable time

Many a times you may need to convert the human readable time into the Unix time. When all the information is passed to “mktime” it returns the unixtime. And to reverse it simply use “localtime”. Here is the example.

use POSIX;
use strict;
use warnings;

my $sec = 6;
my $min = 7;
my $hour = 8;
my $day = 9;
my $mon = 10 - 1;
my $year = 2004 - 1900;
my $wday = 0;
my $yday = 0;

my $unixtime = mktime ($sec, $min, $hour, $day, $mon, $year, $wday, $yday);
print "$unixtimen";

my $readable_time = localtime($unixtime);
print "$readable_timen";

Found at http://www.adp-gmbh.ch/perl/posix/convert_time.html