begin process at 2012 05 27 21:53:23
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Réseau & Internet

 > IP CALCULATOR

IP CALCULATOR


 Information sur la source

Note :
9,25 / 10 - par 4 personnes
9,25 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :Réseau & Internet Classé sous :ipcalc, network, broadcast, conversion, convertisseur Niveau :Expert Date de création :10/08/2009 Date de mise à jour :18/12/2009 08:23:59 Vu / téléchargé :6 945 / 461

Auteur : X_Cli

Ecrire un message privé
Commentaire sur cette source (19)
Ajouter un commentaire et/ou une note

 Description

Cette classe est la version PHP du programme unix ipcalc. Il permet de calculer à partir d'une adresse IP (en binaire, hexadécimal ou au format xxx.xxx.xxx.xxx (dotted quad)) et d'un masque de sous-réseau (en binaire, hexadécimal, dotted quad ou décimal) fournis en paramètres les informations suivantes :
* Réseau
* adresse de Broadcast
* Plus petite adresse IP du sous réseau
* Plus grande adresse IP du sous réseau
* Adresse IP précédente
* Adresse IP suivante
* Réseau précédent
* Réseau suivant
* Nombre d'adresses IP dans le sous réseau

Elle permet également de tester si une adresse fait parti du même sous réseau qu'une autre.
Elle permet également la conversion des adresses d'un format à l'autre via des fonctions statiques et le calcul du réseau et de l'adresse de broadcast en statique.

Source

  • Fichier de test :
  • <?php
  • define('NL', "\n");
  • require('IP4Calc.class.php');
  • echo('Test for 172.23.10.221/16'.NL);
  • $oIP = new IP4Calc('172.23.10.221', '16');
  • echo('Netmask (Quad): '.$oIP->get(IP4Calc::NETMASK, IP4Calc::QUAD_DOTTED).NL);
  • echo('Netmask (Bin): '.$oIP->get(IP4Calc::NETMASK, IP4Calc::BIN).NL);
  • echo('Netmask (Hex): '.$oIP->get(IP4Calc::NETMASK, IP4Calc::HEX).NL);
  • echo('Network (Quad): '.$oIP->get(IP4Calc::NETWORK, IP4Calc::QUAD_DOTTED).NL);
  • echo('Broadcast (Quad): '.$oIP->get(IP4Calc::BROADCAST, IP4Calc::QUAD_DOTTED).NL);
  • echo('Lowest IP address of the subnet (Quad): '.$oIP->get(IP4Calc::MIN_HOST, IP4Calc::QUAD_DOTTED).NL);
  • echo('Highest IP address of the subnet (Quad): '.$oIP->get(IP4Calc::MAX_HOST, IP4Calc::QUAD_DOTTED).NL);
  • echo('The previous IP address (Quad): '.$oIP->get(IP4Calc::PREVIOUS_HOST, IP4Calc::QUAD_DOTTED).NL);
  • echo('The next IP address (Quad): '.$oIP->get(IP4Calc::NEXT_HOST, IP4Calc::QUAD_DOTTED).NL);
  • echo('The previous network with the same netmask (Quad): '.$oIP->get(IP4Calc::PREVIOUS_NETWORK, IP4Calc::QUAD_DOTTED).NL);
  • echo('THe next network with the same netmask (Quad): '.$oIP->get(IP4Calc::NEXT_NETWORK, IP4Calc::QUAD_DOTTED).NL);
  • echo('The number of IP address usable for hosts in this subnet: '.$oIP->count().NL);
  • echo('Is 172.23.254.10 part of this subnet ? ');
  • var_dump($oIP->partOf('172.23.254.10'));
  • echo('Is 192.168.1.100 part of this subnet ? ');
  • var_dump($oIP->partOf('192.168.1.100'));
  • ?>
  • Code de la classe :
  • <?php
  • if(!defined('IP4CALC_CLASS')) {
  • define('IP4CALC_CLASS', true);
  • /**
  • * This class is about converting IPv4 addresses between the different format available and
  • * calculating informations out of the IPv4 and netmask provided.
  • * @package IP4Calc
  • * @author Florian MAURY <pub[DASH]ip4calc[AT]x[DASH]cli[DOT]com>
  • * @version 1.1, 08/18/09
  • * @history 08/18/09 Integrating the constants in the class, adding checks for the get function
  • */
  • class IP4Calc {
  • // Definition of constants to abstract the usage from the internal namespace
  • const IP='IP';
  • const NETMASK='Netmask';
  • const NETWORK='Network';
  • const BROADCAST='Broadcast';
  • const MIN_HOST='MinHost';
  • const MAX_HOST='MaxHost';
  • const PREVIOUS_HOST='PrevHost';
  • const NEXT_HOST='NextHost';
  • const PREVIOUS_NETWORK='PrevNetwork';
  • const NEXT_NETWORK='NextNetwork';
  • const INT32='Int32';
  • const BIN='Bin';
  • const HEX='Hex';
  • const QUAD_DOTTED='Quad';
  • const DECIMAL='Dec';
  • /**
  • * Contains data provided, calculated and cached about the IP address used in this instance
  • * @access private
  • * @var Array
  • */
  • private $aAddresses;
  • /**
  • * @access public
  • * @param string $sIP IP address in binary, hexadecimal or dotted quad format
  • * @param mixed $mNetmask The netmask of the IP address in binary, hexadecimal, dotted quad or decimal (e.g. 24 for xxx.xxx.xxx.xxx/24)
  • * @throws Exception If the IP address or the netmask are not provided in a valid format
  • */
  • public function __construct($sIP, $mNetmask) {
  • $this->aAddresses = array();
  • $this->aAddresses[self::IP] = array();
  • $this->aAddresses[self::NETMASK] = array();
  • $this->aAddresses[self::NETWORK] = array();
  • $this->aAddresses[self::BROADCAST] = array();
  • $this->aAddresses[self::MIN_HOST] = array();
  • $this->aAddresses[self::MAX_HOST] = array();
  • $this->aAddresses[self::PREVIOUS_HOST] = array();
  • $this->aAddresses[self::NEXT_HOST] = array();
  • $this->aAddresses[self::PREVIOUS_NETWORK] = array();
  • $this->aAddresses[self::NEXT_NETWORK] = array();
  • list($sFormat, $iIP) = $this->convertIPToInt32($sIP);
  • $this->aAddresses[self::IP][$sFormat] = $sIP;
  • $this->aAddresses[self::IP][self::INT32] = $iIP;
  • // Detecting deciaml format for netmask
  • if(preg_match('/^[0-9]{1,2}$/', (string) $mNetmask) > 0 && (integer) $mNetmask <= 32) {
  • $this->aAddresses[self::NETMASK][self::DECIMAL] = (integer) $mNetmask;
  • $this->aAddresses[self::NETMASK][self::INT32] = self::convertDecToInt32((integer) $mNetmask);
  • }
  • // Detecting Quad dotted format for netmask
  • elseif(preg_match('/^((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))$/', (string)$mNetmask, $aQuad) > 0) {
  • $this->aAddresses[self::NETMASK][self::QUAD_DOTTED] = $mNetmask;
  • array_shift($aQuad); // Removing the first field containing the whole string
  • $this->aAddresses[self::NETMASK][self::INT32] = self::convertQuadToInt32($aQuad);
  • }
  • // Detecting hexadecimal format for netmask
  • elseif(preg_match('/^(?:Ox)?(?:([0-9a-f])[:.\-]?$)/i', (string)$mNetmask, $aHex) > 0) {
  • $this->aAddresses[self::NETMASK][self::HEX] = $mNetmask;
  • $this->aAddresses[self::NETMASK][self::INT32] = self::convertHexToInt32($aHex);
  • }
  • // Detecting binary format for netmask
  • elseif(preg_match('/^[0-1]{32}$/', (string)$mNetmask) > 0) {
  • $this->aAddresses[self::NETMASK][self::BIN] = $mNetmask;
  • $this->aAddresses[self::NETMASK][self::INT32] = self::convertBinToInt32($mNetmask);
  • }
  • else {
  • throw new Exception('Unknown format for this netmask parameter.');
  • }
  • }
  • /**
  • * Convert an IP address from the dotted quad format to an unsigned int32.
  • * @access public
  • * @static
  • * @param mixed $mQuad The IP address to convert. Can be a string containing the dotted quad address or a 4 slots array.
  • * @throws Exception the parameter is not a valid dotted quad IP address
  • * @return uint32 Since PHP doesn't handle unsigned int, it's a float.
  • */
  • static public function convertQuadToInt32($mQuad) {
  • if(is_string($mQuad) === true) {
  • // Checking the ip format + removing the eventual netmask
  • if(preg_match('/^((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))$/i', $mQuad, $aQuad) > 0) {
  • array_shift($aQuad); // Removing the first field containing the whole string
  • }
  • else {
  • throw new Exception('Bad format. Expect a quad dotted address.');
  • }
  • }
  • else {
  • $aQuad = $mQuad;
  • }
  • $iInt32Format = 0;
  • for($i = 0 ; $i < 4 ; $i++) {
  • $iInt32Format += (integer)$aQuad[3 - $i] * pow(2,8*$i);
  • }
  • return $iInt32Format;
  • }
  • /**
  • * Convert an IP address from an unsigned int32 to a dotted quad.
  • * @access public
  • * @static
  • * @param uint32 $iQuad The IP address to convert. Since PHP does'nt handle unsigned int, this is a float.
  • * @return string A dotted quad address
  • */
  • static public function convertInt32ToQuad($iQuad) {
  • $mask = pow(2, 8) - 1;
  • return (string)(($iQuad / pow(2,24)) & $mask).'.'.(string)(($iQuad / pow(2,16)) & $mask).'.'.(string)(($iQuad / pow(2,8)) & $mask).'.'.(string)($iQuad & $mask);
  • }
  • /**
  • * Convert an IP address from a hexadecimal expression to an unsigned int32.
  • * @access public
  • * @static
  • * @param mixed $mHex The IP address to convert in hexadecimal. Can be a string representing the hexadecimal number or a 4 slots array.
  • * @return uint32 Since PHP doesn't handle unsigned int, it's a float.
  • */
  • static public function convertHexToInt32($mHex) {
  • $sHex='';
  • if(is_array($mHex) === true) {
  • $sHex = implode('', $mHex);
  • }
  • return hexdec($sHex);
  • }
  • /**
  • * Convert an IP address from an unsigned int32 to a hexadecimal expression.
  • * @access public
  • * @static
  • * @param uint32 $iHex The IP address to convert. Since PHP doesn't handle unsigned int, it's a float.
  • * @return string The IP address in the hexadecimal format
  • */
  • static public function convertInt32ToHex($iHex) {
  • return '0x'.dechex($iHex);
  • }
  • /**
  • * Convert an IP address from binary format to an unsigned int32.
  • * @access public
  • * @static
  • * @param string $sBin The IP address to convert. It's a 32 Bytes string of 1 and 0.
  • * @return uint32 Since PHP doesn't handle unsigned int, it's a float.
  • */
  • static public function convertBinToInt32($sBin) {
  • return bindec($sBin);
  • }
  • /**
  • * Convert an IP address from an unsigned int32 to a string of 1 and 0 (binary format).
  • * @access public
  • * @static
  • * @param uint32 $iBin The IP address to convert. Since PHP doesn't handle unsigned int, it's a float.
  • * @return string It's a string of 1 and 0 representing the ip address in binary
  • */
  • static public function convertInt32ToBin($iBin) {
  • return decbin($iBin);
  • }
  • /**
  • * Convert a netmask from the short decimal format to an unsigned int32
  • * @access public
  • * @static
  • * @param integer $iNetmask A short decimal netmask (e.g. 27 for xxx.xxx.xxx.xxx/27)
  • * @return uint32 The netmask in uint32 format. Since PHP doesn't handle unsigned int32, it's a float
  • */
  • static public function convertDecToInt32($iNetmask) {
  • $iInt32Format = 0;
  • for($i = 0 ; $i < $iNetmask ; $i++) {
  • $iInt32Format += pow(2,31-$i);
  • }
  • return $iInt32Format;
  • }
  • /**
  • * Convert a netmask from an unsigned int32 to a short decimal
  • * @access public
  • * @static
  • * @param uint32 $iNetmask The netmask in uint32 format. Since PHP doesn't handle unsigned int32, it's a float
  • * @return integer A short decimal netmask (e.g. 27 for xxx.xxx.xxx.xxx/27)
  • */
  • static public function convertInt32ToDec($iNetmask) {
  • $iDecFormat = 0;
  • $bOver = false;
  • for($i = 0 ; $i < 32 && $bOver === false ; $i++) {
  • if((($iNetmask / pow(2,31-$i)) & 1) !== 0) {
  • $iDecFormat++;
  • }
  • else {
  • $bOver = true;
  • }
  • }
  • return $iDecFormat;
  • }
  • /**
  • * Get the network address of the given IP/Netmask couple
  • * @access public
  • * @static
  • * @param uint32 $iIP An IP address from the subnet for which you want the network address. Since PHP doesn't handle unsigned int32, it's a float
  • * @param uint32 $iNetmask The netmask of the subnet for which you want the network address. Since PHP doesn't handle unsigned int32, it's a float
  • * @return uint32 The network IP address in uint32 format. Since PHP doesn't handle unsigned int32, it's a float
  • */
  • static public function getNetwork($iIP, $iNetmask) {
  • // Little trick to solve the problem of the unability of PHP to do bitwise operation on unsigned int32.
  • // I don't want to force people to use the gmp module
  • $mask=pow(2,16) - 1;
  • return (((($iIP / pow(2,16)) & $mask) & (($iNetmask / pow(2,16)) & $mask)) * pow(2,16)) + (($iIP & $mask) & ($iNetmask & $mask));
  • }
  • /**
  • * Get the broadcast address of the given IP/Netmask couple
  • * @access public
  • * @static
  • * @param uint32 $iIP An IP address from the subnet for which you want the broadcast address. Since PHP doesn't handle unsigned int32, it's a float
  • * @param uint32 $iNetmask The netmask of the subnet for which you want the broadcast address. Since PHP doesn't handle unsigned int32, it's a float
  • * @return uint32 The broadcast IP address in uint32 format. Since PHP doesn't handle unsigned int32, it's a float
  • */
  • static public function getBroadcast($iIP, $iNetmask) {
  • return self::getNetwork($iIP,$iNetmask) + ((pow(2,32) - 1) - $iNetmask);
  • }
  • /**
  • * Get the IP addresses of the different element that can be generated from the IP address given in the constructor.
  • * @access public
  • * @param string $sTarget The name of the element you want to get. Please, use the constants defined at the beginning of this file
  • * @param string $sType The name of the return type of the element you want to get. Please, use the constants defined at the beginning of this file
  • * @throws Exception If the $sTarget parameter is not a valid target
  • * @return mixed The element requested in the type requested. Can be null if the element requested doesn't exist (case of previous host, previous network, next host, next network)
  • */
  • public function get($sTarget, $sType) {
  • switch($sTarget) {
  • case self::IP:
  • case self::NETMASK:
  • case self::NETWORK:
  • case self::BROADCAST:
  • case self::MIN_HOST:
  • case self::MAX_HOST:
  • case self::PREVIOUS_HOST:
  • case self::NEXT_HOST:
  • case self::PREVIOUS_NETWORK:
  • case self::NEXT_NETWORK:
  • break;
  • default:
  • throw new Exception('Unknown target.');
  • break;
  • }
  • switch($sType) {
  • case self::INT32:
  • case self::QUAD_DOTTED:
  • case self::HEX:
  • case self::BIN:
  • break;
  • case self::DECIMAL:
  • if($sTarget !== self::NETMASK) {
  • throw new Exception('Invalid format for this target');
  • }
  • break;
  • default:
  • throw new Exception('Invalid format');
  • break;
  • }
  • if(false === isset($this->aAddresses[$sTarget][$sType])) {
  • if(false === isset($this->aAddresses[$sTarget][self::INT32])) {
  • $this->compute($sTarget);
  • }
  • if($sType !== self::INT32) {
  • $sFunctionName = 'convertInt32To'.$sType;
  • $this->aAddresses[$sTarget][$sType] = self::$sFunctionName($this->aAddresses[$sTarget][self::INT32]);
  • }
  • }
  • return $this->aAddresses[$sTarget][$sType];
  • }
  • /**
  • * Get the number of IP addresses in the subnet of the IP provided in the constructor
  • * @access public
  • * @return integer The number of IP addresses in the subnet
  • */
  • public function count() {
  • return (pow(2,32) - 1) - $this->get(self::NETMASK, self::INT32) - 1;
  • }
  • /**
  • * Test if an IP address is part of the subnet of the IP address provided in the constructor
  • * @access public
  • * @param string $sIP The IP address to test
  • * @return boolean True if the IP address provided is in the subnet, otherwise false
  • */
  • public function partOf($sIP) {
  • list($sFormat, $iIP) = $this->convertIPToInt32($sIP);
  • return ($this->get(self::MIN_HOST, self::INT32) <= $iIP && $this->get(self::MAX_HOST, self::INT32) >= $iIP);
  • }
  • /**
  • * Compute the int32 format of the element requested in parameter and store it in the addresses table property of the class
  • * @access private
  • * @param string $sTarget The name of the element to be computed
  • * @throws Exception If the $sTarget parameter is not a valid target
  • */
  • private function compute($sTarget) {
  • switch($sTarget) {
  • case self::NETWORK:
  • $this->aAddresses[$sTarget][self::INT32] = self::getNetwork($this->get(self::IP, self::INT32), $this->get(self::NETMASK, self::INT32));
  • break;
  • case self::BROADCAST:
  • $this->aAddresses[$sTarget][self::INT32] = self::getBroadcast($this->get(self::IP, self::INT32), $this->get(self::NETMASK, self::INT32));
  • break;
  • case self::MIN_HOST:
  • $this->aAddresses[self::MIN_HOST][self::INT32] = $this->get(self::NETWORK, self::INT32) + 1;
  • break;
  • case self::MAX_HOST:
  • $this->aAddresses[self::MAX_HOST][self::INT32] = $this->get(self::BROADCAST, self::INT32) - 1;
  • break;
  • case self::PREVIOUS_HOST:
  • $this->aAddresses[self::PREVIOUS_HOST][self::INT32] = (($this->get(self::IP, self::INT32) - 1) === $this->get(self::NETWORK, self::INT32))?null:$this->get(self::IP, self::INT32) - 1;
  • break;
  • case self::NEXT_HOST:
  • $this->aAddresses[self::NEXT_HOST][self::INT32] = (($this->get(self::IP, self::INT32) + 1) === $this->get(self::BROADCAST, self::INT32))?null:$this->get(self::IP, self::INT32) + 1;
  • break;
  • case self::PREVIOUS_NETWORK:
  • $this->aAddresses[self::PREVIOUS_NETWORK][self::INT32] = ($this->get(self::NETWORK, self::INT32) === 0)?null:self::getNetwork($this->get(self::NETWORK, self::INT32) - 1, $this->get(self::NETMASK, self::INT32));
  • break;
  • case self::NEXT_NETWORK:
  • $this->aAddresses[self::NEXT_NETWORK][self::INT32] = ($this->get(self::BROADCAST, self::INT32) === (255*pow(2,24) + 255*pow(2,16) + 255 * pow(2,8) + 255))?null:$this->get(self::BROADCAST, self::INT32) + 1;
  • break;
  • default:
  • throw new Exception('Unknown compute target.');
  • }
  • }
  • /**
  • * Convert an IP address in any format into a uint32
  • * @access private
  • * @param string $sIP The IP address to convert
  • * @throws Exception If the $sIP parameter is not a valid IP address
  • * @return array(string, uint32) The format detected and the IP address in uint32 format. Since PHP doesn't handle unsigned int32, it's a float.
  • */
  • private function convertIPToInt32($sIP) {
  • // Detecting Quad Dotted format for ip
  • if(preg_match('/^((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))$/', $sIP, $aQuad) > 0) {
  • array_shift($aQuad); // Removing the first field containing the whole string
  • $sFormat = self::QUAD_DOTTED;
  • $iIP = self::convertQuadToInt32($aQuad);
  • }
  • // Detecting hexadecimal format for ip
  • elseif(preg_match('/^(?:Ox)?(?:([0-9a-f])[:.\-]?$)/i', $sIP, $aHex) > 0) {
  • array_shift($aHex); // Removing the first field containing the whole string
  • $sFormat = self::HEX;
  • $iIP = self::convertHexToInt32($aHex);
  • }
  • // Detecting binary format for ip
  • elseif(preg_match('/^[0-1]{32}$/', $sIP) > 0) {
  • $sFormat = self::BIN;
  • $iIP = self::convertBinToInt32($sIp);
  • }
  • // IP is not provided in a valid format
  • else{
  • throw new Exception('Unknown format for the IP parameter.');
  • }
  • return array($sFormat, $iIP);
  • }
  • }
  • }
  • ?>
Fichier de test :
<?php
define('NL', "\n");
require('IP4Calc.class.php');

echo('Test for 172.23.10.221/16'.NL);
$oIP = new IP4Calc('172.23.10.221', '16');
echo('Netmask (Quad): '.$oIP->get(IP4Calc::NETMASK, IP4Calc::QUAD_DOTTED).NL);
echo('Netmask (Bin): '.$oIP->get(IP4Calc::NETMASK, IP4Calc::BIN).NL);
echo('Netmask (Hex): '.$oIP->get(IP4Calc::NETMASK, IP4Calc::HEX).NL);
echo('Network (Quad): '.$oIP->get(IP4Calc::NETWORK, IP4Calc::QUAD_DOTTED).NL);
echo('Broadcast (Quad): '.$oIP->get(IP4Calc::BROADCAST, IP4Calc::QUAD_DOTTED).NL);
echo('Lowest IP address of the subnet (Quad): '.$oIP->get(IP4Calc::MIN_HOST, IP4Calc::QUAD_DOTTED).NL);
echo('Highest IP address of the subnet (Quad): '.$oIP->get(IP4Calc::MAX_HOST, IP4Calc::QUAD_DOTTED).NL);
echo('The previous IP address (Quad): '.$oIP->get(IP4Calc::PREVIOUS_HOST, IP4Calc::QUAD_DOTTED).NL);
echo('The next IP address (Quad): '.$oIP->get(IP4Calc::NEXT_HOST, IP4Calc::QUAD_DOTTED).NL);
echo('The previous network with the same netmask (Quad): '.$oIP->get(IP4Calc::PREVIOUS_NETWORK, IP4Calc::QUAD_DOTTED).NL);
echo('THe next network with the same netmask (Quad): '.$oIP->get(IP4Calc::NEXT_NETWORK, IP4Calc::QUAD_DOTTED).NL);
echo('The number of IP address usable for hosts in this subnet: '.$oIP->count().NL);
echo('Is 172.23.254.10 part of this subnet ? ');
var_dump($oIP->partOf('172.23.254.10'));
echo('Is 192.168.1.100 part of this subnet ? ');
var_dump($oIP->partOf('192.168.1.100'));
?>


Code de la classe : 
<?php
if(!defined('IP4CALC_CLASS')) {
define('IP4CALC_CLASS', true);


/**
 * This class is about converting IPv4 addresses between the different format available and
 * calculating informations out of the IPv4 and netmask provided.
 * @package IP4Calc
 * @author Florian MAURY <pub[DASH]ip4calc[AT]x[DASH]cli[DOT]com>
 * @version 1.1, 08/18/09
 * @history 08/18/09 Integrating the constants in the class, adding checks for the get function
*/
class IP4Calc {
    // Definition of constants to abstract the usage from the internal namespace
    const IP='IP';
    const NETMASK='Netmask';
    const NETWORK='Network';
    const BROADCAST='Broadcast';
    const MIN_HOST='MinHost';
    const MAX_HOST='MaxHost';
    const PREVIOUS_HOST='PrevHost';
    const NEXT_HOST='NextHost';
    const PREVIOUS_NETWORK='PrevNetwork';
    const NEXT_NETWORK='NextNetwork';
    const INT32='Int32';
    const BIN='Bin';
    const HEX='Hex';
    const QUAD_DOTTED='Quad';
    const DECIMAL='Dec';

    /**
     * Contains data provided, calculated and cached about the IP address used in this instance
     * @access private
     * @var Array
    */
    private $aAddresses;

    /**
     * @access public
     * @param string $sIP IP address in binary, hexadecimal or dotted quad format
     * @param mixed $mNetmask The netmask of the IP address in binary, hexadecimal, dotted quad or decimal (e.g. 24 for xxx.xxx.xxx.xxx/24)
     * @throws Exception If the IP address or the netmask are not provided in a valid format
    */
    public function __construct($sIP, $mNetmask) {
        $this->aAddresses = array();
        $this->aAddresses[self::IP] = array();
        $this->aAddresses[self::NETMASK] = array();
        $this->aAddresses[self::NETWORK] = array();
        $this->aAddresses[self::BROADCAST] = array();
        $this->aAddresses[self::MIN_HOST] = array();
        $this->aAddresses[self::MAX_HOST] = array();
        $this->aAddresses[self::PREVIOUS_HOST] = array();
        $this->aAddresses[self::NEXT_HOST] = array();
        $this->aAddresses[self::PREVIOUS_NETWORK] = array();
        $this->aAddresses[self::NEXT_NETWORK] = array();

        list($sFormat, $iIP) = $this->convertIPToInt32($sIP);
        $this->aAddresses[self::IP][$sFormat] = $sIP;
        $this->aAddresses[self::IP][self::INT32] = $iIP;

        // Detecting deciaml format for netmask
        if(preg_match('/^[0-9]{1,2}$/', (string) $mNetmask) > 0 && (integer) $mNetmask <= 32) {
            $this->aAddresses[self::NETMASK][self::DECIMAL] = (integer) $mNetmask;
            $this->aAddresses[self::NETMASK][self::INT32] = self::convertDecToInt32((integer) $mNetmask);
        }
        // Detecting Quad dotted format for netmask
        elseif(preg_match('/^((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))$/', (string)$mNetmask, $aQuad) > 0) {
            $this->aAddresses[self::NETMASK][self::QUAD_DOTTED] = $mNetmask;
            array_shift($aQuad); // Removing the first field containing the whole string
            $this->aAddresses[self::NETMASK][self::INT32] = self::convertQuadToInt32($aQuad);
        }
        // Detecting hexadecimal format for netmask
        elseif(preg_match('/^(?:Ox)?(?:([0-9a-f])[:.\-]?$)/i', (string)$mNetmask, $aHex) > 0) {
            $this->aAddresses[self::NETMASK][self::HEX] = $mNetmask;
            $this->aAddresses[self::NETMASK][self::INT32] = self::convertHexToInt32($aHex);
        }
        // Detecting binary format for netmask
        elseif(preg_match('/^[0-1]{32}$/', (string)$mNetmask) > 0) {
            $this->aAddresses[self::NETMASK][self::BIN] = $mNetmask;
            $this->aAddresses[self::NETMASK][self::INT32] = self::convertBinToInt32($mNetmask);
        }
        else {
            throw new Exception('Unknown format for this netmask parameter.');
        }
    }
    
    /**
     * Convert an IP address from the dotted quad format to an unsigned int32.
     * @access public
     * @static
     * @param mixed $mQuad The IP address to convert. Can be a string containing the dotted quad address or a 4 slots array.
     * @throws Exception the parameter is not a valid dotted quad IP address
     * @return uint32 Since PHP doesn't handle unsigned int, it's a float.
    */
    static public function convertQuadToInt32($mQuad) {
        if(is_string($mQuad) === true) {
            // Checking the ip format + removing the eventual netmask
            if(preg_match('/^((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))$/i', $mQuad, $aQuad) > 0) {
                array_shift($aQuad); // Removing the first field containing the whole string
            }
            else {
                throw new Exception('Bad format. Expect a quad dotted address.');
            }
        }
        else {
            $aQuad = $mQuad;
        }
        $iInt32Format = 0;
        for($i = 0 ; $i < 4 ; $i++) {
            $iInt32Format += (integer)$aQuad[3 - $i] * pow(2,8*$i);
        }
        return $iInt32Format;
    }

    /**
     * Convert an IP address from an unsigned int32 to a dotted quad.
     * @access public
     * @static
     * @param uint32 $iQuad The IP address to convert. Since PHP does'nt handle unsigned int, this is a float.
     * @return string A dotted quad address
    */
    static public function convertInt32ToQuad($iQuad) {
        $mask = pow(2, 8) - 1;
        return (string)(($iQuad / pow(2,24)) & $mask).'.'.(string)(($iQuad / pow(2,16)) & $mask).'.'.(string)(($iQuad / pow(2,8)) & $mask).'.'.(string)($iQuad & $mask);
    }

    /**
     * Convert an IP address from a hexadecimal expression to an unsigned int32.
     * @access public
     * @static
     * @param mixed $mHex The IP address to convert in hexadecimal. Can be a string representing the hexadecimal number or a 4 slots array.
     * @return uint32 Since PHP doesn't handle unsigned int, it's a float.
    */
    static public function convertHexToInt32($mHex) {
        $sHex='';
        if(is_array($mHex) === true) {
            $sHex = implode('', $mHex);
        }
        return hexdec($sHex);
    }

    /**
     * Convert an IP address from an unsigned int32 to a hexadecimal expression.
     * @access public
     * @static
     * @param uint32 $iHex The IP address to convert. Since PHP doesn't handle unsigned int, it's a float.
     * @return string The IP address in the hexadecimal format
    */
    static public function convertInt32ToHex($iHex) {
        return '0x'.dechex($iHex);
    }

    /**
     * Convert an IP address from binary format to an unsigned int32.
     * @access public
     * @static
     * @param string $sBin The IP address to convert. It's a 32 Bytes string of 1 and 0.
     * @return uint32 Since PHP doesn't handle unsigned int, it's a float.
    */
    static public function convertBinToInt32($sBin) {
        return bindec($sBin);
    }

    /**
     * Convert an IP address from an unsigned int32 to a string of 1 and 0 (binary format).
     * @access public
     * @static
     * @param uint32 $iBin The IP address to convert. Since PHP doesn't handle unsigned int, it's a float.
     * @return string It's a string of 1 and 0 representing the ip address in binary
    */
    static public function convertInt32ToBin($iBin) {
        return decbin($iBin);
    }

    /**
     * Convert a netmask from the short decimal format to an unsigned int32
     * @access public
     * @static
     * @param integer $iNetmask A short decimal netmask (e.g. 27 for xxx.xxx.xxx.xxx/27)
     * @return uint32 The netmask in uint32 format. Since PHP doesn't handle unsigned int32, it's a float
    */
    static public function convertDecToInt32($iNetmask) {
        $iInt32Format = 0;
        for($i = 0 ; $i < $iNetmask ; $i++) {
            $iInt32Format += pow(2,31-$i);
        }
        return $iInt32Format;
    }

    /**
     * Convert a netmask from an unsigned int32 to a short decimal
     * @access public
     * @static
     * @param uint32 $iNetmask The netmask in uint32 format. Since PHP doesn't handle unsigned int32, it's a float
     * @return integer A short decimal netmask (e.g. 27 for xxx.xxx.xxx.xxx/27)
    */
    static public function convertInt32ToDec($iNetmask) {
        $iDecFormat = 0;
        $bOver = false;
        for($i = 0 ; $i < 32 && $bOver === false ; $i++) {
            if((($iNetmask / pow(2,31-$i)) & 1) !== 0) {
                $iDecFormat++; 
            }
            else {
                $bOver = true;
            }
        }
        return $iDecFormat;
    }

    /**
     * Get the network address of the given IP/Netmask couple
     * @access public
     * @static
     * @param uint32 $iIP An IP address from the subnet for which you want the network address. Since PHP doesn't handle unsigned int32, it's a float 
     * @param uint32 $iNetmask The netmask of the subnet for which you want the network address. Since PHP doesn't handle unsigned int32, it's a float 
     * @return uint32 The network IP address in uint32 format. Since PHP doesn't handle unsigned int32, it's a float
    */
    static public function getNetwork($iIP, $iNetmask) {
	// Little trick to solve the problem of the unability of PHP to do bitwise operation on unsigned int32.
	// I don't want to force people to use the gmp module
        $mask=pow(2,16) - 1;
        return (((($iIP / pow(2,16)) & $mask) & (($iNetmask / pow(2,16)) & $mask)) * pow(2,16)) + (($iIP & $mask) & ($iNetmask & $mask));
    }

    /**
     * Get the broadcast address of the given IP/Netmask couple
     * @access public
     * @static
     * @param uint32 $iIP An IP address from the subnet for which you want the broadcast address. Since PHP doesn't handle unsigned int32, it's a float 
     * @param uint32 $iNetmask The netmask of the subnet for which you want the broadcast address. Since PHP doesn't handle unsigned int32, it's a float 
     * @return uint32 The broadcast IP address in uint32 format. Since PHP doesn't handle unsigned int32, it's a float
    */
    static public function getBroadcast($iIP, $iNetmask) {
        return self::getNetwork($iIP,$iNetmask) + ((pow(2,32) - 1) - $iNetmask); 
    }

    /**
     * Get the IP addresses of the different element that can be generated from the IP address given in the constructor.
     * @access public
     * @param string $sTarget The name of the element you want to get. Please, use the constants defined at the beginning of this file
     * @param string $sType The name of the return type of the element you want to get. Please, use the constants defined at the beginning of this file
     * @throws Exception If the $sTarget parameter is not a valid target
     * @return mixed The element requested in the type requested. Can be null if the element requested doesn't exist (case of previous host, previous network, next host, next network)
    */
    public function get($sTarget, $sType) {
        switch($sTarget) {
            case self::IP:
            case self::NETMASK:
            case self::NETWORK:
            case self::BROADCAST:
            case self::MIN_HOST:
            case self::MAX_HOST:
            case self::PREVIOUS_HOST:
            case self::NEXT_HOST:
            case self::PREVIOUS_NETWORK:
            case self::NEXT_NETWORK:
                break;
            default:
                throw new Exception('Unknown target.');
                break;
        }
        switch($sType) {
            case self::INT32:
            case self::QUAD_DOTTED:
            case self::HEX:
            case self::BIN:
                break;
            case self::DECIMAL:
                if($sTarget !== self::NETMASK) {
                    throw new Exception('Invalid format for this target');
                }
		break;
            default:
                throw new Exception('Invalid format');
                break;
        }

        if(false === isset($this->aAddresses[$sTarget][$sType])) {
            if(false === isset($this->aAddresses[$sTarget][self::INT32])) {
                $this->compute($sTarget);
            }
            if($sType !== self::INT32) {
                $sFunctionName = 'convertInt32To'.$sType;
                $this->aAddresses[$sTarget][$sType] = self::$sFunctionName($this->aAddresses[$sTarget][self::INT32]);
            }
        }
        return $this->aAddresses[$sTarget][$sType];
    }

    /**
     * Get the number of IP addresses in the subnet of the IP provided in the constructor
     * @access public
     * @return integer The number of IP addresses in the subnet
    */
    public function count() {
        return (pow(2,32) - 1) - $this->get(self::NETMASK, self::INT32) - 1;
    }

    /**
     * Test if an IP address is part of the subnet of the IP address provided in the constructor
     * @access public
     * @param string $sIP The IP address to test
     * @return boolean True if the IP address provided is in the subnet, otherwise false
    */
    public function partOf($sIP) {
        list($sFormat, $iIP) = $this->convertIPToInt32($sIP);        
        return ($this->get(self::MIN_HOST, self::INT32) <= $iIP && $this->get(self::MAX_HOST, self::INT32) >= $iIP);
    }

    /**
     * Compute the int32 format of the element requested in parameter and store it in the addresses table property of the class
     * @access private
     * @param string $sTarget The name of the element to be computed
     * @throws Exception If the $sTarget parameter is not a valid target
    */
    private function compute($sTarget) {
        switch($sTarget) {
            case self::NETWORK:
                $this->aAddresses[$sTarget][self::INT32] = self::getNetwork($this->get(self::IP, self::INT32), $this->get(self::NETMASK, self::INT32));
            break;
            case self::BROADCAST:
                $this->aAddresses[$sTarget][self::INT32] = self::getBroadcast($this->get(self::IP, self::INT32), $this->get(self::NETMASK, self::INT32));
            break;
            case self::MIN_HOST:
                $this->aAddresses[self::MIN_HOST][self::INT32] = $this->get(self::NETWORK, self::INT32) + 1;
            break;
            case self::MAX_HOST:
                $this->aAddresses[self::MAX_HOST][self::INT32] = $this->get(self::BROADCAST, self::INT32) - 1;
            break;
            case self::PREVIOUS_HOST:
                $this->aAddresses[self::PREVIOUS_HOST][self::INT32] = (($this->get(self::IP, self::INT32) - 1) === $this->get(self::NETWORK, self::INT32))?null:$this->get(self::IP, self::INT32) - 1; 
            break;
            case self::NEXT_HOST:
                $this->aAddresses[self::NEXT_HOST][self::INT32] = (($this->get(self::IP, self::INT32) + 1) === $this->get(self::BROADCAST, self::INT32))?null:$this->get(self::IP, self::INT32) + 1; 
            break;
            case self::PREVIOUS_NETWORK:
                $this->aAddresses[self::PREVIOUS_NETWORK][self::INT32] = ($this->get(self::NETWORK, self::INT32) === 0)?null:self::getNetwork($this->get(self::NETWORK, self::INT32) - 1, $this->get(self::NETMASK, self::INT32)); 
            break;
            case self::NEXT_NETWORK:
                $this->aAddresses[self::NEXT_NETWORK][self::INT32] = ($this->get(self::BROADCAST, self::INT32) === (255*pow(2,24) + 255*pow(2,16) + 255 * pow(2,8) + 255))?null:$this->get(self::BROADCAST, self::INT32) + 1;
            break;
            default:
                throw new Exception('Unknown compute target.');
        }
    }

    /**
     * Convert an IP address in any format into a uint32
     * @access private
     * @param string $sIP The IP address to convert
     * @throws Exception If the $sIP parameter is not a valid IP address
     * @return array(string, uint32) The format detected and the IP address in uint32 format. Since PHP doesn't handle unsigned int32, it's a float.
    */
    private function convertIPToInt32($sIP) {
        // Detecting Quad Dotted format for ip
        if(preg_match('/^((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))\.((?:1?[0-9]{1,2})|(?:2[0-4][0-9])|(?:25[0-5]))$/', $sIP, $aQuad) > 0) {
            array_shift($aQuad); // Removing the first field containing the whole string
            $sFormat = self::QUAD_DOTTED;
            $iIP = self::convertQuadToInt32($aQuad);
        }
        // Detecting hexadecimal format for ip
        elseif(preg_match('/^(?:Ox)?(?:([0-9a-f])[:.\-]?$)/i', $sIP, $aHex) > 0) {
            array_shift($aHex); // Removing the first field containing the whole string
            $sFormat = self::HEX;
            $iIP = self::convertHexToInt32($aHex);
        }
        // Detecting binary format for ip
        elseif(preg_match('/^[0-1]{32}$/', $sIP) > 0) {
            $sFormat = self::BIN;
            $iIP = self::convertBinToInt32($sIp);
        }
        // IP is not provided in a valid format
        else{
            throw new Exception('Unknown format for the IP parameter.');
        }
        return array($sFormat, $iIP);
    }
}

}
?>


 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 Historique

10 août 2009 11:43:38 :
Typo
10 août 2009 12:50:35 :
typo sur le test (copier coller du mot (quad) sur le nombre d'IP dans un réseau)
10 août 2009 15:15:08 :
Correction d'un commentaire sur function convertIPToInt32 : Le return type n'était pas uint32 mais array(string, uint32)... Commentaire écrit peut être un peu trop vite... je ne sais pas...
11 août 2009 10:32:16 :
Ajout d'un zip, car il ne semble pas pratique de récupérer le code dans la section "Source"
11 août 2009 10:35:19 :
Le code dans le zip n'était pas à jour au niveau des modifs apportées directement dans la section source... désolé :/
11 août 2009 16:29:25 :
Rajout d'un @throws dans les commentaires de la fonction get. En effet, get appelle compute mais propage l'exception que compute peut générer. Techniquement count et partOf devraient aussi propager ou gérer l'exception vu qu'ils utilisent get, mais cela voudrait dire que vous avez modifié les sources et crée un bug car les types sont rentrés en "dur" dans ces fonctions et l'utilisation d'un type invalide ne devrait donc pas être possible
18 août 2009 19:32:46 :
Mise à jour du code en intégrant les constantes dans la classe, et ajout de contrôle dans la fonction get
18 août 2009 20:56:53 :
Update du code source de la case "source" pour refléter les modifs apportées dans le zip
07 octobre 2009 18:07:20 :
Erreur bête dans le constructeur causant un décalage (+8) des masques lorsqu'ils sont donnés sous la forme quad dotted.
18 décembre 2009 08:23:59 :
Un grand merci à lerouxju qui m'a rapporté par message privé deux bugs dans la fonction get. J'avais oublié un break, causant une exception dans certains cas valides et... j'avais utilisé une mauvaise constante, relicat de la version sans constantes de classe, ce qui obfusquait le premier bug. Je pense encore au support des /31 et /32 !

 Sources de la même categorie

INSPECTEUR DE PAGES (VÉRIFIEZ SI DES SITES AFFICHENT UN TEXT... par pablo836
Source avec Zip Source avec une capture GÉOLOCALISATION par pgl10
Source avec Zip TAPI : METTRE EN RELATION DEUX POSTES TELEPHONIQUES par ravery
Source avec Zip CLIENT / SERVEUR : LES SOCKETS par Morphinof
Source avec Zip VALIDATEUR_3WC par lezj

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture CONVERTISSEUR DE NOMBRES EN TEXTE par macruz
Source avec Zip Source avec une capture [POO] OBJET CONVERTISSANT UN NOMBRE DE SECONDES EN DIFFÉRENT... par Dariumis
FORMATER DES MILLISECONDES AU FORMAT HH:MM:SS:MMM par lcef
Source avec Zip DÉBUTANT : FONCTION POUR TRANSFORMER UN TEMPS EN SECONDES EN... par MonkeyIsBack
Source avec Zip CLASSE DE GESTION D'INTERFACE RÉSEAUX par madislak

Commentaires et avis

Commentaire de X_Cli le 14/08/2009 12:22:14

Aucun commentaire... je suis déçu ! Me serais attendu à au moins un mot sur mon expression rationnelle sur les dotted quad ou sur ma fonction getNetwork et l'astuce pour faire un & binaire sur un uint32... C'est qu'il n'y a rien à redire à ma source ? :D

Commentaire de MangaII le 17/08/2009 07:56:19 10/10

Ben si ... y'a des choses à dire !

Pas mal l'expression rationnelle ... mais était-ce vraiment nécessaire ?

Par contre, la clarté du code mérite des points à elle seule !

Je ne l'ai même pas testé, mais un code aussi joli ne peut que fonctionner.

Bravo !

Commentaire de X_Cli le 17/08/2009 09:00:30

Merci :) Disons que ca fait plaisir d'avoir au moins un retour positif, voire un retour tout court ;) Malgré que je programme en PHP depuis plusieurs années (alors que ce n'est pas mon métier... je suis adminsys), c'est la première fois que je poste une source PHP sur un réseau public et j'étais impatient d'être jugé sur mon code, afin d'une part de me situer et d'autre part de corriger des mauvaises habitudes que j'aurai pu prendre.

Commentaire de simonviei le 17/08/2009 10:13:02 8/10

Cette class très intéressante pour d'une part son utilité et puis parce qu'elle me semble bien écrite.

:)

Commentaire de jon1316 le 18/08/2009 04:37:27

J'aurais juste une remarqua à propos des constantes (c'est le seul truc qui m'a choqué ^^), pourquoi ne pas les mettre dans la classes ?

class IP4Calc {
const
IP = 'IP',
NETMASK = 'Netmask',
NETWORK = 'Network',
BROADCAST = 'Broadcast',
MIN_HOST = 'MinHost',
MAX_HOST = 'MaxHost',
PREVIOUS_HOST = 'PrevHost',
NEXT_HOST = 'NextHost',
PREVIOUS_NETWORK = 'PrevNetwork',
NEXT_NETWORK = 'NextNetwork',
INT32 = 'Int32',
BIN = 'Bin',
HEX = 'Hex',
QUAD_DOTTED = 'Quad',
DECIMAL = 'Dec';
....

Et en remplaçant tout les IP4CALC_ par self::

Sinon très bonne source, je la garde sous le coude ;)

Commentaire de X_Cli le 18/08/2009 08:43:24

Hum... après tant d'éloges, ca va être compliqué de le dire ainsi, mais... si je n'ai pas fait mes déclarations ainsi, c'est tout simplement que j'ignorais qu'une telle syntaxe existait, mais je souhaitais qu'elle existe justement... je sais pas comment j'ai fait mon compte pour passer à coté sur google quand je l'ai cherchée :p
Je corrige ça dans l'après midi.
Merci beaucoup pour cette remarque.

Commentaire de jon1316 le 19/08/2009 00:38:37 10/10

Y a pas de quoi
Ce message est destiné à mettre une note ><

Commentaire de Jayadeva le 27/08/2009 22:28:30

Heh, pourquoi t'a des fonctions inutiles ?

Comme :
# static public function convertBinToInt32($sBin) {
#  return bindec($sBin);
# }

Commentaire de X_Cli le 27/08/2009 23:48:52

Bonjour,
Il ne s'agit pas de fonctions inutiles mais de wrappers qui n'ont pas d'autres actions que d'uniformiser le nommage des fonctions (ce qui, pour troller un peu, est rare pour les fonctions internes de PHP =)). Une utilité notoire est ainsi de pouvoir retenir plus facilement les noms des fonctions et de pouvoir exécuter les fonctions en générant leurs noms dans une chaine de caractères via les constantes de type, comme je le fais dans la fonction get. Sans cela, j'aurai pu m'en sortir avec un switch, mais je trouvais cela moins élégant.

Commentaire de megavolts le 31/08/2009 23:43:12 9/10

Genial, exactement ce que je cherchais pour finir une applis réseau.
Cependant un petit bug du a la méthode utilisée: le calcul du MIN_HOST et MAX_HOST avec un subnet en /31 inverse les résultats.

Commentaire de X_Cli le 01/09/2009 08:30:21

Merci pour ce commentaire Megavolts.
Je crois que le bug réside plutôt dans l'acceptation de masques supérieurs à 30, car un /31 ne contient pas d'hôtes du tout, juste un réseau et un broadcast et un /32 ne contient pas du tout de notion de réseau. Je devrais donc abaisser ma limite dans le constructeur à 30. Qu'en penses tu ?

Commentaire de megavolts le 01/09/2009 08:57:05

Le /31 correspond a un lien PtP RFC 3021, dans cette notation il n'existe plus de network ni de brodcast, ces 2 IP sont directement utilisable comme MIN_HOST et MAX_HOST.

Pour l'instant j'ai rajouter un controle pour utiliser le MAX_HOST a la place du MIN_HOST lorsque le masques est en /31

Pour info ipcalc le gère ;-)

Commentaire de X_Cli le 01/09/2009 10:55:29

Ah ! Je ne savais pas. Ce matin, j'ai rapidement lu autour du sujet et vu que c'était rarement usité, et souvent décrié ; mais tu as raison, s'il y a une RFC, je me dois de le supporter. Je corrige ça dans la journée, il faut que je regarde comment je vais gérer ça proprement.
Merci beaucoup pour tes remarques.

Commentaire de X_Cli le 03/09/2009 12:23:45

Je suis un peu sous l'eau, en ce moment ; je corrige dès que je peux. Désolé pour ce délai.

Commentaire de MrJAY42 le 13/09/2009 10:32:19

Hello,

Mais j'ai une question qui peut sembler "bête" :
Pourquoi ? :
Pourquoi tout mettre dans des constantes ? Qui sont modifiées dans le constructeur...
Pourquoi mettre toutes ces constantes dans un tableau ?
Pourquoi ne pas gérer la classe avec des attributs en private avec des get() et des set()...old school pour ainsi dire...

En tout cas merci pour cette classe qui peut être carrément utile :)
Ciao

Commentaire de X_Cli le 13/09/2009 11:34:30

Bonjour,
Désolé, je suis encore sous l'eau en ce moment... mais promis, je pense à corriger le bug des /31 et /32. Je ne vois pas d'autre solution que de faire un hack bien moche "if /31 then" :o/ Cela dit, en lisant la RFC, elle est issue elle-même d'un vieux hack des spécifications des masques :)

Pour répondre à ta question MrJay42, et bien, heu... en fait faudrait déjà que je comprenne :P Je ne modifie pas mes constantes dans le constructeur.
En fait, à l'aide de mes constantes (vraies constantes, j'entends), j'initialise des tableaux. Pourquoi faire ? Pour "cacher" la réponse des calculs. Mettons que tu demandes plusieurs fois la même information, celle ci est cachée, et j'économise les qq microsecondes de calcul... Bon j'avoue, ca doit représenter que dalle, mais je préfère gaspiller un peu de mémoire, le temps que l'objet existe, plutôt que refaire des calculs déjà faits.
Ensuite, j'ai utilisé un tableau, plutôt que des variables sépérarées, pour compacter un peu le code, sans trop le complexifier. J'aurai pu faire un tableau par information (pour le cache), et faire un get par données avec le format en paramètre, il est vrai. C'est juste que c'était plus long à écrire, et assez répétitif, à base de nombreux copier/coller peu intéressants et donc source d'erreur.
Tant que ca reste comprehensible, moins il y a de lignes, moins il y a de bugs possibles :p

Commentaire de MrJAY42 le 13/09/2009 12:30:20

Ok.
C'est donc une justification esthétique et pratique.
Et pardon, j'ai lu un peu trop rapidement le code, en effet les constantes servent d'index dans le tableau "général".
Merci pour ton explication

Commentaire de faischiermarredecreerdescomptespartout le 07/10/2009 16:26:47

J'ai tenté d'utiliser cette classe... cependant elle a du mal avec les notations quad dotted visiblement...

Je lui fourni une ip 10.10.10.10 avec un masque de 255.255.0.0 et j'ai un beau network à 10.10.10.0 (!)

<?php
require('IP4Calc.class.php');
$oIP = new IP4Calc("10.10.10.10", "255.255.0.0");
$network=$oIP->get(IP4Calc::NETWORK, IP4Calc::QUAD_DOTTED);
$broadcast=$oIP->get(IP4Calc::BROADCAST, IP4Calc::QUAD_DOTTED);
echo "Le net serait ".$network;
echo "\nLa diff. serait ".$broadcast;
?>

php test.php
Le net serait 10.10.10.0
La diff. serait 10.10.10.255

La bonne réponse est : 10.10.0.0 et 10.10.255.255

code à revoir...
:)

Commentaire de X_Cli le 07/10/2009 18:10:29

Quel naze je fais :/ C'est corrigé ! Merci
En gros, j'avais oublié que preg_match reproduisait la chaine en case 0, quand j'ai codé le constructeur... ce qui était sioux, c'est que je m'en suis rappelé dans le reste du code :/

Je pense toujours au /31 et /32... mais après le manque de temps, la bronchite... le destin s'acharne :)

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

Conversion BMP vers JPG [ par Manson ] Bonjour a tous,voilà j'aimerai savoir comment l'on peut faire pour convertir un BMP vers un JPG, car je ne trouve aucune fonction le permettant, alors HELP! conversion de variables [ par eax ] comment fait-on pour convertir une variable, par exemple:$toto=12,12,35,25250,251,1,0,2pour l'enregistrer dans un seul champ d'une base de données mys conversion de date [ par Joez ] voila je récupère la date de mysql sous la forme 2002-01-02 10:43:32 et je voudrais afficher cette date sous la forme Lundi 02 janvier 2002 à 10h4 probleme conversion HTML -> Texte -> HTML [ par Cho7Kipu ] Coucou tt le monde !Bon alors j'explik mon probleme :J'ai fait un site de partition. Pour que mon moteur puisse rechercher des mots contenu dans une d conversion d'un script js à php [ par pyranhaz ] Salut,comment convertir ce script javascript en php ???&lt;script language="Javascript"&gt;&lt;!--ID=window.setTimeout("window.location='htt Conversion de caractères issus de dbase.comment faire? [ par asterixobelix ] &lt;?php$base="eleves.dbf";$dbh =dbase_open($base,0);$nb_eleves=dbase_numrecords($dbh);print("$nb_eleves &lt;BR&gt;");$nb_champs=dbase_numfields($dbh) conversion code c++ vers PHP [ par karolina64 ] Bonjour,j'ai le code suivant écrit en C++ que je veux traduire en PHP :Maxord = 12;*snorm = 1.0;for (n=1; n&lt;=maxord; n++) {*(snorm+n) = *(snorm+n-1 conversion fichier .doc en .html [ par thoru ] Bonjour!Je débute en php et je ne sais pas s'il existe une possibilité de convertir un fichier .doc en fichier.html.Je vous explique je dois prendre d convertisseur monétaire [ par attentio ] salut a tous !j'aimerais savoir si il existe des scripts tout fait qui permettent de faire la conversion euro/dollar selon le cour de la bourse. En f Tags Word - Conversion [ par jdaviaud ] Bonjour a tous,J'essaye desespérément de faire une interface d'import de fichiers texte pour les convertir ensuite en fichier HTML, tout fonctionne im


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,468 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales