For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > February 2006 > IP Number/ IP Address Array









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author IP Number/ IP Address Array
overkill@sadiqs.net

2006-02-20, 6:56 pm

Greetings,

I need to convert the first column of a list of IP numbers to IP
addresses. I created an array of my list but am stumped on how to convert
the numbers.

File:
180884576 imstrmcs05
180884577 imstrmcs06
180884578 imstrmcs07
180884579 imstrmcs08
180884580 imstrmcs09
180884581 imstrmcs10


Script:
# Properly formatting into an array
open(IPLIST, "file") || die "couldn't open the file";

while ($x = <IPLIST> )
{
chop $x;
@arr = split /\s+/,$x;
print "@arr\n";
}

# Converting IP number to IP address.
foreach $ipaddr {
$ip1 = int ($ipaddr / (256**3));
$ipaddr %= ($ip1 * 256**3);
$ip2 = int ($ipaddr / (256**2));
$ipaddr %= ($ip2 * 256**2);
$ip3 = int ($ipaddr /256);
$ip4 = $ipaddr % ($ip3 * 256);

$realip=$ip1 . "." . $ip2 . "." . $ip3 . "." . $ip4;
print "$realip\n";
}

close(IPLIST);

John W. Krahn

2006-02-20, 6:56 pm

overkill@iqs.net wrote:
> Greetings,


Hello,

> I need to convert the first column of a list of IP numbers to IP
> addresses. I created an array of my list but am stumped on how to
> convert the numbers.
>
> File:
> 180884576 imstrmcs05
> 180884577 imstrmcs06
> 180884578 imstrmcs07
> 180884579 imstrmcs08
> 180884580 imstrmcs09
> 180884581 imstrmcs10
>
>
> Script:
> # Properly formatting into an array
> open(IPLIST, "file") || die "couldn't open the file";
>
> while ($x = <IPLIST> )
> {
> chop $x;
> @arr = split /\s+/,$x;
> print "@arr\n";
> }
>
> # Converting IP number to IP address.
> foreach $ipaddr {
> $ip1 = int ($ipaddr / (256**3));
> $ipaddr %= ($ip1 * 256**3);
> $ip2 = int ($ipaddr / (256**2));
> $ipaddr %= ($ip2 * 256**2);
> $ip3 = int ($ipaddr /256);
> $ip4 = $ipaddr % ($ip3 * 256);
>
> $realip=$ip1 . "." . $ip2 . "." . $ip3 . "." . $ip4;
> print "$realip\n";
> }
>
> close(IPLIST);


Use the Socket module:

john@d154-20-234-189:~> echo "180884576 imstrmcs05
180884577 imstrmcs06
180884578 imstrmcs07
180884579 imstrmcs08
180884580 imstrmcs09
180884581 imstrmcs10" | perl -le'
use Socket;
while ( <> ) {
my @arr = split;
my $ip = inet_aton $arr[ 0 ];
print inet_ntoa $ip if defined $ip;
}
'
10.200.20.96
10.200.20.97
10.200.20.98
10.200.20.99
10.200.20.100
10.200.20.101




John
--
use Perl;
program
fulfillment
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com