
![]() |
perkiset
This is a
PHPadaptation of NutBallsASPcode 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 whyPHPwas 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 alsolearned something during this exercise - the ^ is not the exponent operator inPHP![]() ![]() 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 learned something during this exercise - the ^ is not the exponent operator inPHPD'oh! ROFLMAOI would have guessed **, but it looks like they implemented it with a function. <edit>was missing a / </edit> perkiset
Here it is done in
PERLby Dirk:http://www.perkiset.org/forum/ perl/converting_ip_addresses_to_integers_and_vice_versa-t174.0.html;newFatty
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 andINET_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 andINET_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 |

Thread Categories

![]() |
![]() |
Best of The Cache Home |
![]() |
![]() |
Search The Cache |
- Ajax
- Apache & mod_rewrite
- BlackHat SEO & Web Stuff
- C/++/#, Pascal etc.
- Database Stuff
- General & Non-Technical Discussion
- General programming, learning to code
- Javascript Discussions & Code
- Linux Related
- Mac, iPhone & OS-X Stuff
- Miscellaneous
- MS Windows Related
- PERL & Python Related
- PHP: Questions & Discussion
- PHP: Techniques, Classes & Examples
- Regular Expressions
- Uncategorized Threads