The CreatorCon Call for Content is officially open! Get started here.

Calculate IP Address Range

karthik120
Giga Expert

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

2 REPLIES 2

dravvyramlochun
ServiceNow Employee
ServiceNow Employee

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

codycotulla
Tera Guru

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.

 

https://community.servicenow.com/community?id=community_question&sys_id=54b1cb69db98dbc01dcaf3231f96...

Good luck.

Thanks,

Cody