[UPHPU] challenge!

Gary Thornock Gary_Thornock at sento.com
Fri Apr 16 12:19:11 MDT 2004


That's great, but what about classless subnets?

:)


-----Original Message-----
From: David Smith [mailto:DavidSmith at byu.net]
Sent: Friday, April 16, 2004 11:51
To: list at uphpu.org
Subject: RE: [UPHPU] challenge!


You just want the first N octets of an IP address as a string with the
rest zeroed? I want to run for the most rigorous error checking and best
documentation award. Anyone care to test?

<?php

// unit tests:
var_dump( ipAddrToSubnetThing( "192.168.5.4", 3 ) );
var_dump( ipAddrToSubnetThing( "253.168.5.4", 2 ) );
var_dump( ipAddrToSubnetThing( "192.168.5.4", 3 ) );
var_dump( ipAddrToSubnetThing( "192.168.5.4", 1 ) );

/**
 * Gets the first N octets of an IP address.
 * @param String $ip The IP address of interest as a string
 *     ("192.168.23.14");
 * @param Integer (optional) The number of octets to extract.
 * @return String The first N octets or false if your params are bad.
 * @example
 *  <code>
 *    $subnet_thing = ipAddrToSubnetThing( "192.5.42.242", 3 );
 *    echo $subnet_thing; // "192.5.42.0"
 *    $subnet_thing = ipAddrToSubnetThing( "192.5.42.242", 2 );
 *    echo $subnet_thing; // "192.5.0.0"
 *  </code>
 */
function ipAddrToSubnetThing( $ip, $num_octets=3 ) {
  if ( ! isValidIpv4Address( $ip ) )
    return false;
  if( ! is_numeric( $num_octets ) )
    return false;
  if( $num_octets < 1 || $num_octets > 4 )
    return false;
  $octets = explode( ".", $ip, 4 );
  if( 4 != count( $octets ) )
    return false;
  for( $i=1; $i<=4-$num_octets; $i++ )
    unset( $octets[ 4 - $i ] );
  $return_octets = implode( '.', $octets );
  for( $i=1; $i<=4-$num_octets; $i++ )
    $return_octets .= '.0';
  return $return_octets;
}

/**
 * Determins whether an IP address is valid.
 * @param String $ip the IP address of interest.
 * @return Boolean True if the IP address is valid, false otherwise.
 */
function isValidIpv4Address( $ip )
{
  $parts = explode( '.', $ip );
  if( count( $parts ) != 4 )
    return false;
  foreach( $parts as $part )
    if( ! is_numeric( $part ) )
      return false;
    elseif( $part > 254 || $part < 0 )
      return false;
  return true;
}
?>


---------------------------------------------------------------------
To unsubscribe, e-mail: list-unsubscribe at uphpu.org
For additional commands, e-mail: list-help at uphpu.org





More information about the UPHPU mailing list