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@sadsix.com

2006-02-20, 6:56 pm


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

T Baetzler

2006-02-20, 6:56 pm


<overkill@six.com> asked:
> I need to convert the first column of a list of IP numbers to=20
> IP addresses. I created an array of my list but am stumped=20
> on how to convert the numbers.


#!/usr/bin/perl

use strict;
use warnings;
use Socket;

sub number_to_ip {

return( inet_ntoa( pack( 'N', $_[0] ) ) );
}

while( <DATA> ){
my( $number, $hostname ) =3D split;
print $hostname . " =3D> " . number_to_ip( $number ) . "\n";
}

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


HTH,
Thomas
Sponsored Links







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

Copyright 2008 codecomments.com