Just for the record, I've been using the following little utility sub for handling IP addresses for a few years now.
sub ipto32bit { # # Convert a dotted quad c.d.e.f to a single unsigned 32bit number. # my ($ip, $c, $d, $e, $f); $ip = shift; ($c,$d,$e,$f) = split(/\./,$ip); return ($c << 24) + ($d << 16) + ($e << 8) + $f; }
Then it's just a matter of doing a straight lexical numerical sort. An example of how this might be used:
#!/usr/bin/perl -wl use strict; chomp(my @ips = <DATA>); my @sorted_ips = sort by_ip(@ips); print for (@sorted_ips); sub by_ip { return ipto32bit($a) <=> ipto32bit($b); } sub ipto32bit { # # Convert a dotted quad c.d.e.f to a single unsigned 32bit number. # my ($ip, $c, $d, $e, $f); $ip = shift; ($c,$d,$e,$f) = split(/\./,$ip); return ($c << 24) + ($d << 16) + ($e << 8) + $f; } __DATA__ 12.345.111.3 12.345.111.26 61.8.47.111 12.345.111.24 203.134.35.27 12.345.111.5 12.345.111.4
Which gives:
12.345.111.3 12.345.111.4 12.345.111.5 12.345.111.24 12.345.111.26 61.8.47.111 203.134.35.27

Note that I started using the above before I learned about the inet_aton goodness that was pointed out by shmem above. So if I was looking for a solution now, shmem's is probably the one I would choose.

Cheers,
Darren :)


In reply to Re: How to sort IP addresses by McDarren
in thread How to sort IP addresses by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.