interger to I P address

James Hess mysidia at gmail.com
Wed Aug 27 18:59:23 CDT 2008


Perl provides some cleaner methods for interpreting/displaying IPs.
There isn't a formal standard notation for an IP that looks like a string of
decimal digits with no dots though.

I.e. no RFC will define the host byte order and tell you that "127.0.0.1"
corresponds to the decimal integer 2130706433;
I might be little-endian and argue that the right human-readable integer
to call that ip is 16777343.

There are a vast number of different numerical representations the
very same ip address could be converted to, because a string of bits has
no inherent representation.  Displaying an IP in a novel format seems dangerous.

Ips have only a binary notation and.. in recent years
dots-and-decimals are formalized.
In general, rather than just in the context of SMTP.
Still conflicting conventions exists that haven't been fixed, for example
try pinging  "127.1"  (hint: it's an old abbreviation mechanism not
merely a "bug")



In any case, to get from quad-octet notation to  a decimal integer
representation you may be thinking of
(if you interpret those octets in the network byte order used for
other items such as port numbers):

$ perl -e 'use IO::Socket; print unpack("N",inet_aton("127.0.0.1"))."\n"'
2130706433

$ perl -e 'use IO::Socket; print inet_ntoa(pack("N",2130706433))."\n";'
127.0.0.1

$ perl -e 'use IO::Socket; print inet_ntoa(pack("N",2066563929))."\n";'
123.45.67.89

And of course...
$ perl -e 'print "",(123<<24)|(45<<16)|(89<<8),"\n"'
2066569472


Or if you don't like one-liners, 3 separate short scripts:


ipv4-to-hex:

#!/usr/bin/perl
use IO::Socket;
printf("%x\n", unpack("N",inet_aton($ARGV[0])));

ipv4-to-integer:
#!/usr/bin/perl
use IO::Socket;
printf("%d\n", unpack("N",inet_aton($ARGV[0])));

hex-to-ipv4:
#!/usr/bin/perl
use IO::Socket;
print inet_ntoa(pack("N",hex($ARGV[0])));



On Wed, Aug 27, 2008 at 9:13 AM, Michael Holstein
<michael.holstein at csuohio.edu> wrote:
>
>> ls it possible t convert the interger to ip
>>
>
> #!/usr/local/bin/perl
> # Perl script to convert between numeric and dotted quad IPs.
> # give credit to Paul Gregg for this one
> while (<STDIN>) {
>  chomp; $input = $_;
>  if (/\./) {
>   ($a, $b, $c, $d) = split(/\./);
>   $decimal = $d + ($c * 256) + ($b * 256**2) + ($a * 256**3);
>  } else {
>   $decimal = $_;
>   $d = $_ % 256; $_ -= $d; $_ /= 256;
>   $c = $_ % 256; $_ -= $c; $_ /= 256;
>   $b = $_ % 256; $_ -= $b; $_ /= 256;
>   $a = $_;
>  }
>
>  if ( ($a>255) || ($b>255) || ($c>255) || ($d>255) ) {
>   print "$0: Invalid input: $input\n";
>  } else {
>   printf ("Address: %d.%d.%d.%d is %u  (Hex:%02x%02x%02x%02x)\n",
> $a,$b,$c,$d, $decimal,$a,$b,$c,$d);
>  }
> }
>
>




More information about the NANOG mailing list