Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Two functions to facilitate IPv4 address comparison

2 views
Skip to first unread message

Chih-Cherng Chin

unread,
Nov 21, 2009, 9:11:29 AM11/21/09
to
To generate reports from mail server log, I often need to sort IPv4
addresses. As the system sort is oriented to string comparison,
the result of direct IPv4 address sorting would look out of place to
human. For example, the sorting of 192.168.3.4 and 192.92.244.3 will
produce:

192.168.3.4
192.92.244.3

while the reverse is right because 92 is smaller than 168.

To remedy that, I wrote an awk function to convert an IPv4 address to
a fixed length string, where every octet is exactly 3 digits. The
code follows:

function fl_ip(ip, a) {
split(ip, a, /\./);
return sprintf("%03d.%03d.%03d.%03d", a[1], a[2], a[3], a[4]);
}
{ print fl_ip($0); }

If "192.92.244.3" is fed to the code above, it will print "192.092.244.003,"
which is suitable for string comparison.

To convert the fixed length string back to an IPv4 address, another
awk function was written:

function plain_ip(ip, s) {
s = "." ip;
gsub(/\.00?/, ".", s);
return substr(s, 2);
}
{ print plain_ip($0); }

These two functions should be very useful for network and system
administrators.

--
Chih-Cherng Chin
Daily Top 10 Botnet Networks and Countries
http://botnet-tracker.blogspot.com/

Loki Harfagr

unread,
Nov 21, 2009, 11:49:55 AM11/21/09
to
Sat, 21 Nov 2009 14:11:29 +0000, Chih-Cherng Chin did cat :

> To generate reports from mail server log, I often need to sort IPv4
> addresses. As the system sort is oriented to string comparison, the
> result of direct IPv4 address sorting would look out of place to human.
> For example, the sorting of 192.168.3.4 and 192.92.244.3 will produce:
>
> 192.168.3.4
> 192.92.244.3

not to diminish the role of your awk function but you would
like to precise that the "system sort" function allows
a few parametres ,-)

using your example:
$ echo "192.168.3.4
> 192.92.244.3" | sort -n -t. -k1,1 -k2,2 -k3,3 -k4,4
192.92.244.3
192.168.3.4

<snip>

0 new messages