The Cache: Technology Expert's Forum
 
*
Welcome, Guest. Please login or register. December 05, 2008, 10:55:47 AM

Login with username, password and session length


Pages: [1]
  Print  
Author Topic: Converting IP Addresses to integers and vice versa  (Read 528 times)
dirk
Global Moderator
Expert
*****
Offline Offline

Posts: 373


View Profile
« on: May 07, 2007, 04:06:57 PM »

Here is the Perl adaptation of the IP conversion.

It's a test script which includes the respective subroutines to
convert the IP address into an integer and vice versa.

Code:
#!/usr/bin/perl

use strict;
use warnings;
use Carp;

my $ip = '255.255.255.255';

my $ip_int = ip_to_int($ip);

my $ip_new = int_to_ip($ip_int);

print "$ip -> $ip_int -> $ip_new\n";

exit;

#-------------------------------------------------------------------------------

sub ip_to_int {
    my ($ip) = @_;

    my $ip_int;
    if ( my ( $ip_a, $ip_b, $ip_c, $ip_d ) =
        $ip =~ m{ ^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$ }xms )
    {
        $ip_int =
            ( $ip_a * 256**3 ) + ( $ip_b * 256**2 ) + ( $ip_c * 256 ) + $ip_d;
    }
    else {
        croak "Invalid IP Address: $ip";
    }

    return $ip_int;
}

#-------------------------------------------------------------------------------

sub int_to_ip {
    my ($ip_int) = @_;

    my $ip =
          ( ( $ip_int / 256**3 ) % 256 ) . q{.}
        . ( ( $ip_int / 256**3 ) % 256 ) . q{.}
        . ( ( $ip_int / 256**3 ) % 256 ) . q{.}
        . ( $ip_int % 256 );

    return $ip;
}

#-------------------------------------------------------------------------------
« Last Edit: May 07, 2007, 04:12:44 PM by dirk » Logged
perkiset
Olde World Hacker
Administrator
Lifer
*****
Online Online

Posts: 5230


:sniffle: Humor was so much easier before.


View Profile
« Reply #1 on: May 07, 2007, 04:12:53 PM »

Nice Dirk and easily readable. Here it is done in PHP as well:

http://www.perkiset.org/forum/php/converting_ip_adrresses_to_integers_and_back-t87.0.html

... perhaps we need to think about how to structure this so that when we have the same functionality described in multiple languages it is easily found and read in that way... gonna have to think about how to do that.

Thanks!

/p
Logged

If I can't be Mr. Root then I don't want to play.
Pages: [1]
  Print  
 
Jump to:  

Perkiset's Place Home   Best of The Cache   phpMyIDE: MySQL Stored Procedures, Functions & Triggers
Politics @ Perkiset's   Pinkhat's Perspective   
cache
mart
coder
programmers
ajax
php
javascript
Powered by MySQL Powered by PHP Powered by SMF 1.1.2 | SMF © 2006-2007, Simple Machines LLC
Seo4Smf v0.2 © Webmaster's Talks


Valid XHTML 1.0! Valid CSS!