Perl

IP Address To decimal and vice-versa using Perl

There can be a situation where we need to convert IPv4 Address(32 bit) from 4 octet format i.e. 127.0.0.1 to  it decimal equivalent value i.e.  2130706433 and vice-versa. We can use pack, unpack in-built Perl functions to achieve this situation or we can use Socket.pm module (if allowed) along with pack and unpack, whichever you feel easier; you can use it in your code.

Perl Version: 5.10
Modules used: Socket.pm (Optional, but I used)
Perl in-built Functions used: pack and unpack

For IPv4 to Decimal format purpose, we can use either of two methods:

#Using pack and unpack functions
join('.',unpack('C4';, pack('N',shift)));
# or use this using Socket module
inet_ntoa(pack('N',shift));

For Decimal format to IPv4 octet format, we can gaain use either of these two methods:

 #Using pack and unpack functions
 unpack('N', pack ('C4', split('\.', shift)));
 # or use unpack and Socket module for this
 unpack('N',inet_aton(shift));

Here is fully working  code for this purpose:
[CODE]:

#!/usr/bin/perl
##################################################
# Author: Sanjeev Jaiswal
# Date: July, 2013
# Description: Take input from user either
# in decimal format and display 4 octet IPv4 address and vice-versa
##########################################################
use strict;
use warnings;
use Socket;

my $instruction = <<INSTRUCTION;
 You can provide either valid IP Address in 4 octet form
 or You can provide IP Address in decimal form
 This program should give you the output either in decimal format
 or would fetch IPv4 Address in 4 octer format.

 Ex: Input -> 2130706433
 Output -> 127.0.0.1
 Input -> 13.202.14.14 and want the output in decimal format
 Output -> 231345678

INSTRUCTION

print $instruction;
print "Enter either IP octet or number in decimal format, \n";

my $user_input = <STDIN>;
chomp $user_input;

print "Input given: $user_input\n";

if($user_input =~ /^\d+$/){
 print int_to_ip($user_input),"\n";
}
else{
 print ip_to_int($user_input), "\n";
}

sub int_to_ip {
 inet_ntoa(pack('N',shift));
}

sub ip_to_int {
 unpack('N',inet_aton(shift));
}

Any comments/suggestions are most welcome. \m/

Comments are closed.