IP addresses in Perl

With Perl you can do many interesting transformations of IP-numbers. Below is two small examples allowing conversions from “IP quad” (xxx.xxx.xxx.xxx) format to a single decimal and back.

sub ip2dec ($) {
    return unpack N => pack CCCC => split /\\./ => shift;
}

sub dec2ip ($) {
    return join '.' => map { ($\_\[0\] >> 8\*(3-$\_)) % 256 } 0 .. 3;
}

In CPAN you can find many modules aimed at using and manipulating IP-addressees. Some include Net::IP and IP::Country.

Mark all messages as read in an imap folder

The follow script marks all files in a folder as read. You need to pass hostname, username and password as commandline parameters to the script and the script is hardwired to mark all files in a folder call “INBOX.spam” (Cyrus IMAP folder naming convention).

#!/usr/bin/perl -w
use strict;

use Mail::IMAPClient::BodyStructure;
use Mail::IMAPClient;

my ($serv, $usr, $pwd) = (@ARGV); # server, username and password as comandline parameters...

my $imap = Mail::IMAPClient->new(Server=>$serv,User=>$usr,Password=>$pwd);
my @folders = $imap->folders;

foreach my $f (@folders) {
  print 	"$f is a folder with ", $imap->message\_count($f), " messages.n";
}

exit();

Parsing RSS feeds

del.icio.us is a neat service for managing an online bookmark collection. With a little bit of Perl and a few CPAN modules, you can fetch your most recent bookmarks and include them as links on your homepage.

The sample script could be used in a cronjob and creates a file on you local server. It downloads my del.icio.us bookmark feed, chops it down to the ten most recent bookmarks and writes a unordered bullet list. You may need to adapt the template to your specific needs.

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

use LWP::Simple;
use XML::RSS;
use HTML::Template;

my $file = 'include_links.txt';

my @links;
my $tmpl = HTML::Template->new(filename => 'rssFetch.tmpl');
my $rss = XML::RSS->new();
my $data = get( 'http://del.icio.us/rss/mahler' ); # RSS Source
$rss->parse( $data );

$#{$rss->{'items'}} = 9; # Only the 10 most recent items

foreach my $item ( @{ $rss->{'items'} } ) {
  push @links, +{ description => $item->{'dc'}->{'subject'},
		  url => $item->{'link'},
		  title => $item->{'title'}
  }
};

$tmpl->param( links => @links );
open (FILEWRITE, ">$file");
print FILEWRITE $tmpl->output();
close FILEWRITE;

exit();
With the included modules you can do a lot of other interesting stuff. The XML::RSS module also includes functionality to create feeds and you could quite easily create aggregated feeds and other cool stuff with Perl and RSS-feeds.

POP3: List messages in mailbox

Lists sender and subject on all mails in mailbox. MIME::WordDecoder is used to parse heads as most mails often has ISO-8859-1 encoded parts. It should be save to test it on any mailbox as it dosn’t change or remove anything from the mailbox.

#!/usr/local/bin/perl -w
use strict;
use Mail::POP3Client;
use MIME::WordDecoder;

my ($serv, $usr, $pwd) = (@ARGV); # server, username and password as comandline parameters...

my $wd = default MIME::WordDecoder;

my $pop = new Mail::POP3Client( USER => $usr, PASSWORD => $pwd, HOST => $serv );
print "Found " . $pop->Count() . " messages.n";
for (my $i = 1; $i <= $pop->Count(); $i++) {
  foreach ( $pop->Head( $i ) ) {
    if (/^(From|Subject):s+/i) {
  print $wd->decode($\_);
    }
  }
  print "n";
}

exit();

Search in a LDAP directory

This example connects to a LDAP server and makes a search for a name. The name was choosen by random (among those who returned an answer from the queried LDAP). The LDAP used in this example includes a binary certificate. To prevent this from trashing you terminal, it is not printed to the screen (binary field filtered in the attribute loop).

#!/usr/bin/perl -w
use strict;

use Net::LDAP;
my $ldap = Net::LDAP->new('directory.certifikat.dk') or die "$@";
$ldap->bind ;    # an anonymous bind

my $mesg = $ldap->search (  # perform a search
                       base   => "c=DK",
                       filter => "(&(cn=Henrik Jensen))"

                      );

$mesg->code && die $mesg->error;

print STDERR "Found " . $mesg->count . "n";
foreach my $entry ($mesg->all\_entries) {
  my  @values = $entry->attributes();
  foreach my $key (@values) {
    print "$key => \\"" . $entry->get\_value($key) ."\\"n" unless ($key =~ /binary/);
  }
}

exit();

Which IMAP-folders exist?

The following script will make a list of which folders exist in an IMAP account. The script requires you pass hostname, accountname and password on the commandline, but it should be quite easy to change as you like.

#!/usr/bin/perl -w
use strict;

use Mail::IMAPClient::BodyStructure;
use Mail::IMAPClient;

my ($serv, $usr, $pwd) = (@ARGV); # server, username and password as comandline parameters...

my $imap = Mail::IMAPClient->new(Server=>$serv,User=>$usr,Password=>$pwd);
my @folders = $imap->folders;

foreach my $f (@folders) {
  print 	"$f is a folder with ", $imap->message\_count($f), " messages.n";
}

exit();

No comments

The option to leave comments on this site has now been disabled. A new version of the website is coming and the pain comments – from time to time – causes with movable type (in terms of comment spam, server load and likewise issues) is really not worth the trouble. You will quite possible be able to leave a comment once the new version is launched, but until then sorry, no comments.

The legacy Pain

When your fresh young company, you can do everything right from the start – choose the right tools, use the best technology and make a lean mean profit machine. When your an elder company, you usually have a lot of legacy and history to carry on. While trying to move this website from Movable Type to a fresh Wordpress engine, I just realized, that a website almost 10 years old, also have a lot of legacy issues, which I need to handle :-)

Top 3 developer vanities (or oversights)

Sometimes web developers forget, that they are not typical net users and develop websites and applications for themselves rather than the intended mainstream users. Too often we let ourselves slip into a “geek to geek world”, and forget, that many of the sites we create are not for geeks, but for common users. Here are the top three mistakes made across a large number of mainstream websites, as I’ve seen them.

To www or not to www that is the question

I usually prefer surfing without www in front of domain names, and I do somehow except the site to act graceful no matter if the www is there or not. If you’ve been surfing with the www extension to this site the past few days, you accidentally hit my test-site with an access denied message. Sorry about that, but a major change is coming… hopefully soon.