Link to home
Start Free TrialLog in
Avatar of tel2
tel2Flag for New Zealand

asked on

Regex to reformat IP address

Hi Experts,

I'm interested to see if there's a simple regex (or other concise option) to convert addresses like this:
    123.45.6.255
to:
    123045006255
i.e. 3 digits for each octet, padding with leading zeros, to they are all 12 digits long with no periods.

Here's the Perl code I wrote:
    ($ip1, $ip2, $ip3, $ip4) = split('\.', $ENV{REMOTE_ADDR});
    $ip_std = sprintf("%03d%03d%03d%03d", $ip1, $ip2, $ip3, $ip4);
And that does the job, but I'm wondering if it can be simplified.

I guess a few regex's could:
    a) Prefix all octets with '00', then
    b) Keep the last 3 digits only, then
    c) Remove the periods.
Sometime like this:
    ($ip = $ENV{REMOTE_ADDR}) =~ s/(\d+?)/00$1/g;
    $ip =~ s/(\d{1,2})(\d\d\d)/$2/g;
    $ip =~ s/\.//g';
But I'm wondering if there's something more elegant.


Also, I'm wondering if I should I be making my website code so it can handle visitors with IPv6 addresses.  When could they start visiting websites?

Thanks.
tel2
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tel2

ASKER

Beautiful work, ozo.

We'll see if anyone can offer alternatives before I close this.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tel2

ASKER

Good answer again, ozo, and it seems you have no competition, so I will now close this.

That last one was an interesting use of a 'for' "loop" (without looping).  Nice work.  Did you use the 'for' purely to make the code a bit (or even a few bytes) more concise, ozo?  I guess this is the long-hand alternative:
    ($ip = $ENV{REMOTE_ADDR}) =~ s/(\d+)/00$1/g;
    $ip =~ s/0*(\d{3})\.?/$1/g;

Thanks for your efforts (x4).

TRS
Illustrating some variations.  I didn't think you were asking for just one way to do one thing, since you already had that.
You could mix and match among the techniques to come up with a lot more combinations, but I just wanted to give a few examples of some of the techniques so you could decide for yourself which combination you like best.
Other functions that might be used include eval and (un)pack, but in this application it didn't seem to end up simplified.
Avatar of tel2

ASKER

Thanks ozo.

Yes, it's good to see all those different options.