perkiset

This is a

PHP

  adaptation of NutBalls

ASP

  code for storing IP addresses as big ints. I have made this about as efficient as I know how... if anyone else has ideas that'd be great. Note that if you use the defined constants then you'll need to "include" this code rather than put it inline - that's because the defines will happen _after_ your code alls the functions and you'll get nasty Div by Zero errors. Also, in the IntToIP conversion I just couldn't figure out why

PHP

  was returning the 2s compliment of the value rather than the real deal... probably something to do with the mod operator. Anyway, this works correctly. I also

learn

 ed something during this exercise - the ^ is not the exponent operator in

PHP

  Applause  Applause


define('_OCT0', pow(256, 3));
define('_OCT1', pow(256, 2));
define('_OCT2', 256);
function IPtoInt($inStr)
{
if (!preg_match('/([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})/', $inStr, $parts))
throw new Exception("IPtoInt: Invalid IP Address ($inStr)");

return ($parts[1] * _OCT0) + ($parts[2] * _OCT1) + ($parts[3] * _OCT2) + $parts[4];
}

function InttoIP($inInt)
{
$oct4 = $inInt % 256;
$oct4 = ($oct4 < 0) ? 256 + $oct4 : $oct4;
return
(($inInt / _OCT0) % 256) . '.' .
(($inInt / _OCT1) % 256) . '.' .
(($inInt / _OCT2) % 256) . '.' .
$oct4;
}

cdc

quote
I also

learn

 ed something during this exercise - the ^ is not the exponent operator in

PHP

  D'oh!  ROFLMAO


I would have guessed **, but it looks like they implemented it with a function.

<edit>was missing a / </edit>

perkiset

Here it is done in

PERL

  by Dirk:

http://www.perkiset.org/forum/

perl

 /converting_ip_addresses_to_integers_and_vice_versa-t174.0.html;new

Fatty

Since you're multiplying by powers of 2 why not use shifts?

IP_int = octet1 << 24 + octet2 << 16 + octect3 << 8 + octet4

If you're storing in a DB as an int you've got

INET

 _ATON and

INET

 _NTOA... Let the DB worry about it.

Fatty

perkiset

quote author=Fatty link=topic=87.msg1073#msg1073 date=1178732570

IP_int = octet1 << 24 + octet2 << 16 + octect3 << 8 + octet4

You're completely right Fatty - that'd be easier on the math processing I believe.

quote author=Fatty link=topic=87.msg1073#msg1073 date=1178732570

If you're storing in a DB as an int you've got

INET

 _ATON and

INET

 _NTOA... Let the DB worry about it.

Dirk covered that in a discussion about this very topic - these threads are more about just leaving code out there for someone with a specific need ie., "I need to do it in

PHP

 ." - but thanks

/p


Perkiset's Place Home   Politics @ Perkiset's