Translate

Archives

Image of Advanced Programming in the UNIX Environment, Second Edition (Addison-Wesley Professional Computing Series)
Image of Modern Operating Systems (3rd Edition)
Image of XSLT 2.0 and XPath 2.0 Programmer's Reference (Programmer to Programmer)
Image of Linux Kernel Development (3rd Edition)

Using Perl Net::IP to Manipulate IPv4 Addresses

In a previous post, I demonstrated a Korn shell script which determined the subnet mask for a range of IPv4 addresses. Perl has a module called Net::IP which provides a number of functions which can be used to manipulate IPv4 (and also IPv6) addresses to provide the same information and a lot more besides.

For example, the following code outputs a lot of information about a classless prefix:

use Net::IP;

my $ip = new Net::IP ('10.1.1.0/24') or die (Net::IP::Error());
print ("IP  : ".$ip->ip()."n");
print ("Sho : ".$ip->short()."n");
print ("Bin : ".$ip->binip()."n");
print ("Int : ".$ip->intip()."n");
print ("Mask: ".$ip->mask()."n");
print ("Last: ".$ip->last_ip()."n");
print ("Len : ".$ip->prefixlen()."n");
print ("Size: ".$ip->size()."n");
print ("Type: ".$ip->iptype()."n");
print ("Rev:  ".$ip->reverse_ip()."n");


gives

Mask: 255.255.255.128
Prefix: 10.1.1.0/25
IP  : 10.1.1.0
Sho : 10.1.1
Bin : 00001010000000010000000100000000
Int : 167837952
Mask: 255.255.255.0
Last: 10.1.1.255
Len : 24
Size: 256
Type: PRIVATE
Rev:  1.1.10.in-addr.arpa.

The following example determines the subnet prefix for a range of addresses:

my $ip = new Net::IP('10.1.1.0-10.1.1.127') or die(Net::IP::Error());
print("Mask: ".$ip->mask()."n");
print("Prefix: ".$ip->prefix()."n");


gives

Mask: 255.255.255.128
Prefix: 10.1.1.0/25

1 comment to Using Perl Net::IP to Manipulate IPv4 Addresses

  • Manish

    hi,

    I have a subnet and subnet length. like 192.168.1.0 length 8. how do I convert this in CIDR form like 192.168.1.0/29 ?
    is there is straight way function for this ?

    Regards,
    -Manish