Calculate IP Address Range
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-27-2018 12:26 AM
Does anyone know how to check IP address is within the subnet?
Requirement: User will enter the IP address. Using client script I need to check if the entered IP address is within IP range using subnet.
Any help or suggestion appreciated..!
Thanks
- Labels:
-
Scripting and Coding
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-27-2018 01:00 AM
Have a look at the following links:
https://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-network-in-python
or try this code:
/** | |
* Check if a given ip is in a network | |
* @param string $ip IP to check in IPV4 format eg. 127.0.0.1 | |
* @param string $range IP/CIDR netmask eg. 127.0.0.0/24, also 127.0.0.1 is accepted and /32 assumed | |
* @return boolean true if the ip is in this range / false if not. | |
*/ | |
function ip_in_range( $ip, $range ) { | |
if ( strpos( $range, '/' ) == false ) { | |
$range .= '/32'; | |
} | |
// $range is in IP/CIDR format eg 127.0.0.1/24 | |
list( $range, $netmask ) = explode( '/', $range, 2 ); | |
$range_decimal = ip2long( $range ); | |
$ip_decimal = ip2long( $ip ); | |
$wildcard_decimal = pow( 2, ( 32 - $netmask ) ) - 1; | |
$netmask_decimal = ~ $wildcard_decimal; | |
return ( ( $ip_decimal & $netmask_decimal ) == ( $range_decimal & $netmask_decimal ) ); | |
} |
Reference: https://gist.github.com/tott/7684443
Thanks,
Dravvy
Please Hit Helpful or Correct depending on the impact of the response

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-04-2020 08:55 AM
Hi,
Take a look at Chuck Tomasi's script include for finding if an IP is in a network range. What he does should help you figure out what you need to do.
Good luck.
Thanks,
Cody