Converting dotted-quad IP addresses to integers
posted 2009-04-18 09:18:18, link to this article
Some years ago, before I was lazy enough to just grab a module from CPAN, I wrote this handy Perl function to convert a dotted quad IP address to an integer.
sub dotquadToInt($) {
my ($e, $m, $r) = (24,,);
my @octet = split(/\./, $_[0]);
foreach $m (@octet) {
$r += $m*2**$e;
$e -= 8;
};
return $r;
}
I think the above is pretty, because it is easy to adapt to different bases etc. But it is also needlessly complex, a more elegant way to achieve the same is something like this:
sub dotquadToInt($) {
my @octet = split(/\./, $_[0]);
return $octet[0]*2**24 + $octet[1]*2**16 + $octet[2]*2**8 + $octet[3];
}
Maybe these functions are of use to someone, though I would recommend everybody to use the excellent Net::IP Perl module instead!
Dreft
posted 2009-04-18 08:38:53, link to this article
Dreft is a quick and dirty tool that I wrote some time ago to do a bunch of reverse DNS lookups for a CIDR block.Its a pretty simple script, the most interesting part is the ugly workaround to create an in-addr.arpa address from a Net::IP object, somehow I couldn't convince Net::IP to do this for me when iterating addresses.
Usage is pretty straightforward too:
hessch@blokje:~$ dreft 4.2.2.0/29 4.2.2.1 -> vnsc-pri.sys.gtei.net. 4.2.2.2 -> vnsc-bak.sys.gtei.net. 4.2.2.3 -> vnsc-lc.sys.gtei.net. 4.2.2.4 -> vnsc-pri-dsl.genuity.net. 4.2.2.5 -> vnsc-bak-dsl.genuity.net. 4.2.2.6 -> vnsc-lc-dsl.genuity.net.
Below you'll find the complete script, or as a handy downloadable link here.
#!/usr/bin/perl -w
# dreft - reverse dns enumerator
# Hessel Schut, hessel@isquared.nl, 2008-06-24
use strict;
use Net::DNS;
use Net::IP;
my $ip = new Net::IP ($ARGV[0]) or die (Net::IP::Error());
my $res = Net::DNS::Resolver->new;
do {
# $ip->reverse_ip doesn't work when iterating IP addresses
# horrible kludge to in-addr.arpafy the current IP:
my $ptr = join('.', reverse(split /\./, $ip->ip()));
$ptr .= ".in-addr.arpa";
my $rr = $res->query($ptr, qw(PTR));
if ($rr) {
print $ip->ip()." -> ".(($rr->answer)[0]->rdatastr)."\n";
};
} while (++$ip);
Sorting IP addresses
posted 2009-04-13 09:28:03, link to this article
Ever noticed how the Unix sort command can't make anything of IP addresses when you use just a numeric sort, like this:
hessch@galileo:~$ sort -n ip.txt 1.2.3.4 5.6.7.8 10.200.219.5 10.20.30.40 10.3.5.6 89.2.177.21 193.18.4.1
As you notice, for instance 10.20.30.40 is listed below 10.200.219.5, which is wrong, of course. The trick is to define every octect in the dotted quad notation as a key for sort like this:
hessch@galileo:~$ sort -t. -n -k1,1 -k2,2 -k3,3 -k4,4 ip.txt 1.2.3.4 5.6.7.8 10.3.5.6 10.20.30.40 10.200.219.5 89.2.177.21 193.18.4.1
There you have it, using sort -t. -n -k1,1 -k2,2 -k3,3 -k4,4 all addresses are sorted properly.
isquared.nl rss (atom)