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)); }

Replies are listed 'Best First'.
Re: Converting decimal IP addresses to binary
by AgentM (Curate) on Jan 30, 2001 at 23:49 UTC
    It should would be nice if you could extend these examples to recognize and manipulate IPv6-level IPs- especially in a tutorial about TCP/IP.
    AgentM Systems nor Nasca Enterprises nor Bone::Easy nor Macperl is responsible for the comments made by AgentM. Remember, you can build any logical system with NOR.
      IPv6 is beyond the scope of my tutorial which is for internal staff training, but I don't mind doing IPv6 versions of my conversion functions for PM. Should I add the IPv6 versions to the snippets I've already submitted or should I create new ones? I'm still a bit new here and not sure of monkly etiquette.

      ----
      Coyote

        Heck, I'd be more willing to ++ a plus that had more effort put into it (++IPv6). One question though, aren't your functions functionally equivalent to the inet_xxx series combined with an sprintf to return a human-readable string?
        AgentM Systems nor Nasca Enterprises nor Bone::Easy nor Macperl is responsible for the comments made by AgentM. Remember, you can build any logical system with NOR.