|
-
Apr 6th, 2012, 10:15 AM
#1
Thread Starter
Fanatic Member
[RESOLVED] Check if valid IP Address
Hey guys,
Trying to workout a way to check if an IP address if is in the same network from the network address and the subnet mask. Also reporting back the broadcast address would be useful.
It's been a few years since I've had to do any binary calculatotions, especially in PHP.
Can anyone point me in the correct direction? Not sure if there's some functions for it already built into PHP either. Google search hasn't really helped (Sure there's guides, but nothing for PHP).
The normal subnet masks are easy to calculate, like 255.255.0.0 for class B etc - you can hardcode the logic for them. It's the trickier ones that are harder. Basically breaking down the IP address and subnet mask into binary and running XOR functions on them?
-
Apr 6th, 2012, 11:16 AM
#2
Thread Starter
Fanatic Member
Re: Check if valid IP Address
Don't worry... figured it out!
Code:
function checkIPAddress($ipAddressCheck, $networkAddress, $subnetMask)
{
$subnetBin=(pow(2,32)-1)-(pow(2,32-$subnetMask)-1);
$firstIP=ip2long($networkAddress) & ($subnetBin);
$NetworkLength=pow(2,32-$subnetMask)-1;
$longIPAddressCheck = ip2long($ipAddressCheck);
if ($longIPAddressCheck > $firstIP && $longIPAddressCheck < ($firstIP + $NetworkLength))
{
return "true";
}
else
{
return "false";
}
}
-
Apr 6th, 2012, 11:43 AM
#3
Thread Starter
Fanatic Member
Re: Check if valid IP Address
This is for longhand or shorthand subnet masks.
Code:
function checkIPAddress($ipAddressCheck, $networkAddress, $subnetMask)
{
$shorthandSubnet=convertSubnetToShorthand($subnetMask); //Remove this line if you want $subnetMask to take shorthand subnet inputs (eg $subnetMask="8"; for /8 (255.0.0.0)
$subnetBin=(pow(2,32)-1)-(pow(2,32-$shorthandSubnet)-1);
$firstIP=ip2long($networkAddress) & ($subnetBin);
$NetworkLength=pow(2,32-$shorthandSubnet)-1;
$longIPAddressCheck = ip2long($ipAddressCheck);
if ($longIPAddressCheck > $firstIP && $longIPAddressCheck < ($firstIP + $NetworkLength))
{
return "true";
}
else
{
return "false";
}
}
function convertSubnetToShorthand($subnetMask)
{
$subnetOctets=explode(".", $subnetMask, 4);
$reconcatinateSubnetMaskCount="";
for ($octetIndex = 0; $octetIndex <= 3; $octetIndex++)
{
$subnetBinaryIndex[$octetIndex]=decbin($subnetOctets[$octetIndex]);
$reconcatinateSubnetMaskCount=$reconcatinateSubnetMaskCount . $subnetBinaryIndex[$octetIndex];
}
return substr_count($reconcatinateSubnetMaskCount, "1");
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|