[Challenge] IPv4 subnet mask validator

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: [Challenge] IPv4 subnet mask validator

Post by Apollo »

Weirdan wrote:
Mordred wrote:But of course the "boring" solution is faster
Are you sure? In my tests table lookup was slower than Vlad's solution.
How does it compare to my solution, speed-wise?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: [Challenge] IPv4 subnet mask validator

Post by VladSun »

Apollo wrote:Bit trickery FTW:

Code: Select all

function isValidIPv4Mask($mask)
{
  $m = ~ip2long($mask);	
  return $m && ~$m && !($m&($m+1));
}
I've modified it a bit to correct the "Unsupported operand types" fatal error:

Code: Select all

function isValidIPv4Mask2($mask)
{
	if (!$m = ip2long($mask))
		return false;
	
	$m =~ $m;
	return $m && ~$m && !($m&($m+1));
}
Speed test: 0.516259908676 seconds :)

The "original" Mordred's solution has the same speed results.

So it's faster then my "loop" solution. I thought the bottleneck would be the ip2long() function, but obviously it's not true :)

Very, very nice solutions :) I think it's Mordred who deserves the prize :)
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Re: [Challenge] IPv4 subnet mask validator

Post by Mordred »

Meh, I screwed up (I misread some details in the problem description). I can only take credit for the "bit trickery" idea, I was surprised noone tried this approach.
Post Reply