Created
September 16, 2013 23:37
-
-
Save slav123/6588140 to your computer and use it in GitHub Desktop.
check if IP is within the mask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$ipthing = "192.168.1.201"; | |
$ipsubthing = "*.*.*.201"; | |
if(isipinsub ($ipthing, $ipsubthing)) {echo "It's in the subnet."; } else { echo "Nope."; } | |
#---------------------------------# | |
#------isipinsub function---------# | |
#---------------------------------# | |
#--checks whether an IP is in a---# | |
#--subnet. Can understand single--# | |
#--IPs, CIDR-style and 'asterisk'-# | |
#----style entries. Returns as----# | |
#------either true or false.------# | |
#----Needs ipto32bin function.----# | |
#------Cjwinnit@codingforums------# | |
#---------------------------------# | |
function isipinsub ( $ip, $ipsub ) | |
{ | |
$x = strpos($ipsub, "/"); | |
$y = strpos($ipsub, "*"); | |
//The next if statement works out | |
//if it contains (an) asterisk(s) or a slash. | |
//If it has neither, we treat it as a single IP | |
//and we go straight to the comparison at the end. | |
if (!($x === false) || !($y === false)) | |
{ | |
//so it's either CIDR-style or asterisk. | |
//do different things to each... | |
if (!($x === false)) | |
{ | |
//it's CIDR-style. Nick the end number. | |
$lengthcomp = substr($ipsub, $x + 1); | |
//trim off the end number and slash. | |
$ipsub = substr($ipsub, 0, $x); | |
//next two lines trim the binary strings | |
//to the correct length using $lengthcomp. | |
$ip = substr(ipto32bin($ip),0,$lengthcomp); | |
$ipsub = substr(ipto32bin($ipsub),0,$lengthcomp); | |
//We'll go-compaa-AARE! at the end. | |
} else { | |
//Asterisk-style. Bit more complicated... | |
$asteriskarraysub = explode(".",$ipsub); | |
$asteriskarray = explode(".",$ip); | |
//do an element-by-element comparison. | |
$iinf = 0; do { | |
if (!(($asteriskarraysub[$iinf] == $asteriskarray[$iinf]) || ($asteriskarraysub[$iinf] == "*"))) { return FALSE; } | |
$iinf++; | |
} while($iinf<=3); | |
//each of the elements in original IP pairs up | |
//with either it's own number in subip or "*" in subip. | |
//Therefore it's in the subnet. | |
return TRUE; | |
} | |
} | |
//It's where you go to, | |
//Insure your motor.... | |
if($ip === $ipsub) return TRUE; | |
else return FALSE; | |
} | |
#------isipinsub function end-----# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment