Perl: Split IP address into hostid and netid

766 views Asked by At

Simple enough, I'd like to split a given IP address into netid (as defined by the netmask) and the hostid in Perl. Example:

    $network = NetAddr::IP->new('192.168.255.255/29') || die "invalid space $_";

Now $network->mask returns 255.255.255.248. But there're no methods in NetAddr::IP to apply the mask to split the address into its netid and hostid portions in the /29 space.

NetAddr::IP::Util mentions the operators to do so, but it's documentation is a mess.

At least the netid can be extracted using Net::NetMask:

    $netid = Net::Netmask->new('192.168.255.255/29')->base;

This yields 192.168.255.248. Again, no method to get the host portion 0.0.0.7. Maybe the best would be to pack/unpack the IPs into 32 bit int and then simply & them out. Then it would be easier to print the binary representations of IP addresses too, which I found can be really helpful for debugging and documentation purposes.

1

There are 1 answers

1
Pradeep On

Use the hostmask() method

$host_wildcard = Net::Netmask->new('192.168.255.255/29')->hostmask;