This is a small subroutine to convert a decimal IP address to its binary equivalent. The function takes an IP address and an optional delimter to separate the bytes. I am in the process of writing a small tutorial on the basics of TCP/IP networking and I'm using this function to generate examples. It might also be useful for determining CIDR style netmasks (192.168.10.0/24) such as those used by nmap and Apache allow/deny directives with a little work.

ip2bin('255.255.255.0', ' ')
returns
11111111 11111111 11111111 00000000

Update:

Another way to do this is to use the inet_aton function in the Socket module. A perl one liner to produce the same output:

perl -MSocket -e 'printf ("%s %s %s %s", unpack('B8B8B8B8', inet_aton('255.255.255.0')))'

Thanks AgentM for the pointer.

sub ip2bin{ my ($ip, $delimiter) = @_; return join($delimiter, map substr(unpack("B32",pack("N",$_)),-8), split(/\./,$ip)); }

In reply to Converting decimal IP addresses to binary by Coyote

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.