function _get_ranges(&$config) { // get all ip ranges $ranges = array(); foreach ($config as $carrier => $carrier_ips) { foreach ($carrier_ips as $cidr) { $cidr = @Net_IPv4::parseAddress($cidr); $ranges[] = array('broadcast' => $this->ip2double($cidr->broadcast), 'carrier' => $carrier, 'network' => $this->ip2double($cidr->network)); } } // sort usort($ranges, array($this, 'compareByNetwork')); // unite sequent ip range $l = count($ranges); $cur =& $ranges[0]; for ($i = 1; $i < $l; $i++) { $next =& $ranges[$i]; $condition = $cur['broadcast'] + 1 === $next['network'] && $cur['carrier'] === $next['carrier']; if ($condition) { $cur['broadcast'] = $next['broadcast']; unset($ranges[$i]); } else { $cur =& $ranges[$i]; } } $ranges = array_values($ranges); // compile data $retval = "<?php\n" . "// auto-generated by %s\n" . "// date: %s\n" . "return %s;\n"; $retval = sprintf($retval, __CLASS__, date('Y/m/d H:i:s'), var_export($ranges, true)); return $retval; }
function testWillcom() { $this->mobile_ip->initialize($this->controller); $ranges = $this->ranges['willcom']; foreach ($ranges as $cidr) { $cidr = @Net_IPv4::parseAddress($cidr); $network = explode('.', $cidr->network); $broadcast = explode('.', $cidr->broadcast); $ip = "{$network[0]}.{$network[1]}.{$network[2]}"; for ($i = $network[3]; $i <= $broadcast[3]; $i++) { $this->assertEqual($this->mobile_ip->carrier("{$ip}.{$i}"), 'willcom'); } } }
function netmask2cidr($netmask) { $addr = Net_IPv4::parseAddress("1.2.3.4/{$netmask}"); return $addr->bitmask; }
<?php echo 'IPv4 Addresses : '; $oids = trim(snmp_walk($device, 'ipAdEntIfIndex', '-Osq', 'IP-MIB')); $oids = str_replace('ipAdEntIfIndex.', '', $oids); foreach (explode("\n", $oids) as $data) { $data = trim($data); list($oid, $ifIndex) = explode(' ', $data); $mask = trim(snmp_get($device, "ipAdEntNetMask.{$oid}", '-Oqv', 'IP-MIB')); $addr = Net_IPv4::parseAddress("{$oid}/{$mask}"); $network = $addr->network . '/' . $addr->bitmask; $cidr = $addr->bitmask; if (dbFetchCell('SELECT COUNT(*) FROM `ports` WHERE device_id = ? AND `ifIndex` = ?', array($device['device_id'], $ifIndex)) != '0' && $oid != '0.0.0.0' && $oid != 'ipAdEntIfIndex') { $port_id = dbFetchCell('SELECT `port_id` FROM `ports` WHERE `device_id` = ? AND `ifIndex` = ?', array($device['device_id'], $ifIndex)); if (dbFetchCell('SELECT COUNT(*) FROM `ipv4_networks` WHERE `ipv4_network` = ?', array($network)) < '1') { dbInsert(array('ipv4_network' => $network), 'ipv4_networks'); // echo("Create Subnet $network\n"); echo 'S'; } $ipv4_network_id = dbFetchCell('SELECT `ipv4_network_id` FROM `ipv4_networks` WHERE `ipv4_network` = ?', array($network)); if (dbFetchCell('SELECT COUNT(*) FROM `ipv4_addresses` WHERE `ipv4_address` = ? AND `ipv4_prefixlen` = ? AND `port_id` = ?', array($oid, $cidr, $port_id)) == '0') { dbInsert(array('ipv4_address' => $oid, 'ipv4_prefixlen' => $cidr, 'ipv4_network_id' => $ipv4_network_id, 'port_id' => $port_id), 'ipv4_addresses'); // echo("Added $oid/$cidr to $port_id ( $hostname $ifIndex )\n $i_query\n"); echo '+'; } else { echo '.'; } $full_address = "{$oid}/{$cidr}|{$ifIndex}"; $valid_v4[$full_address] = 1; } else { echo '!';
* * @package observium * @subpackage discovery * @author Adam Armstrong <*****@*****.**> * @copyright (C) 2006 - 2013 Adam Armstrong * */ include "includes/defaults.inc.php"; include "config.php"; include "includes/definitions.inc.php"; include "includes/functions.php"; $handle = fopen("ips.txt", "w"); foreach (dbFetchRows("SELECT * FROM `ipv4_networks`") as $data) { $cidr = $data['ipv4_network']; list($network, $bits) = explode("/", $cidr); if ($bits != '32' && $bits != '32' && $bits > '22') { $addr = Net_IPv4::parseAddress($cidr); $broadcast = $addr->broadcast; $ip = ip2long($network) + '1'; $end = ip2long($broadcast); while ($ip < $end) { $ipdotted = long2ip($ip); if (dbFetchCell("SELECT COUNT(ipv4_address_id) FROM `ipv4_addresses` WHERE `ipv4_address` = ?", array($ipdotted)) == '0' && match_network($config['nets'], $ipdotted)) { fputs($handle, $ipdotted . "\n"); } $ip++; } } } fclose($handle); shell_exec("fping -t 100 -f ips.txt > ips-scanned.txt");
/** * Reformat incomplete IPv4 address to decimal for search! */ function reformatIPv4forSearch($ip) { //remove % sign if present $ip = str_replace("%", "", $ip); //remove last . $size = count($ip); $lastChar = substr($ip, -1); if ($lastChar == ".") { $ip = substr($ip, 0, -1); } /* check if subnet provided, then we have all we need */ if (strpos($ip, "/") > 0) { require_once 'PEAR/Net/IPv4.php'; $net = Net_IPv4::parseAddress($ip); $result['low'] = transform2decimal($net->network); $result['high'] = transform2decimal($net->broadcast); } else { /* if subnet is not provided maye wildcard is, so explode it to array */ $ip = explode(".", $ip); //4 is ok if (sizeof($ip) == 4) { $temp = implode(".", $ip); $result['low'] = $result['high'] = transform2decimal($temp); } else { if (sizeof($ip) == 3) { $ip[3] = 0; $result['low'] = transform2decimal(implode(".", $ip)); $ip[3] = 255; $result['high'] = transform2decimal(implode(".", $ip)); } else { if (sizeof($ip) == 2) { $ip[2] = 0; $ip[3] = 0; $result['low'] = transform2decimal(implode(".", $ip)); $ip[2] = 255; $ip[3] = 255; $result['high'] = transform2decimal(implode(".", $ip)); } else { if (sizeof($ip) == 1) { $ip[1] = 0; $ip[2] = 0; $ip[3] = 0; $result['low'] = transform2decimal(implode(".", $ip)); $ip[1] = 255; $ip[2] = 255; $ip[3] = 255; $result['high'] = transform2decimal(implode(".", $ip)); } else { $result['low'] = implode(".", $ip); $result['high'] = implode(".", $ip); } } } } } //return result! return $result; }
/** * Determines whether or not the supplied IP is within the supplied network. * * This function determines whether an IP address is within a network. * The IP address ($ip) must be supplied in dot-quad format, and the * network ($network) may be either a string containing a CIDR * formatted network definition, or a Net_IPv4 object. * * @param string $ip A quad-dot representation of an IP address * @param string $network A string representing the network in CIDR format or a Net_IPv4 object. * @return boolean true if the IP address exists within the network */ function ipInNetwork($ip, $network) { if (!is_object($network) || get_class($network) != 'net_ipv4') { $network = Net_IPv4::parseAddress($network); } if (!is_object($network) || get_class($network) != 'net_ipv4') { return $network; } $net = Net_IPv4::ip2double($network->network); $bcast = Net_IPv4::ip2double($network->broadcast); $ip = Net_IPv4::ip2double($ip); unset($network); if ($ip >= $net && $ip <= $bcast) { return TRUE; } return FALSE; return (double) sprintf("%u", ip2long($ip)); }
/** * Determines whether or not the supplied IP is within the supplied network. * * This function determines whether an IP address is within a network. * The IP address ($ip) must be supplied in dot-quad format, and the * network ($network) may be either a string containing a CIDR * formatted network definition, or a Net_IPv4 object. * * @param string $ip A dot quad representation of an IP address * @param string $network A string representing the network in CIDR format or a Net_IPv4 object. * @return bool true if the IP address exists within the network */ function ipInNetwork($ip, $network) { if (!is_object($network) || strcasecmp(get_class($network), 'net_ipv4') != 0) { $network = Net_IPv4::parseAddress($network); } if (strcasecmp(get_class($network), 'pear_error') === 0) { return false; } $net = Net_IPv4::ip2double($network->network); $bcast = Net_IPv4::ip2double($network->broadcast); $ip = Net_IPv4::ip2double($ip); unset($network); if ($ip >= $net && $ip <= $bcast) { return true; } return false; }
} if (isset($opts['n'])) { $force_network = true; } if (isset($opts['b'])) { $force_broadcast = true; } if (isset($opts['r'])) { $net = Net_IPv4::parseAddress($opts['r']); if (ip2long($net->network) !== false) { perform_snmp_scan($net, $force_network, $force_broadcast); echo 'Scanned ' . $stats['count'] . ' IPs, Already known ' . $stats['known'] . ' Devices, Added ' . $stats['added'] . ' Devices, Failed to add ' . $stats['failed'] . ' Devices.' . PHP_EOL; echo 'Runtime: ' . (microtime(true) - $ts) . ' secs' . PHP_EOL; } else { echo 'Could not interpret supplied CIDR noted IP-Range: ' . $opts['r'] . PHP_EOL; exit(2); } } elseif (isset($config['nets']) && !empty($config['nets'])) { if (!is_array($config['nets'])) { $config['nets'] = array($config['nets']); } foreach ($config['nets'] as $subnet) { $net = Net_IPv4::parseAddress($subnet); perform_snmp_scan($net, $force_network, $force_broadcast); } echo 'Scanned ' . $stats['count'] . ' IPs, Already know ' . $stats['known'] . ' Devices, Added ' . $stats['added'] . ' Devices, Failed to add ' . $stats['failed'] . ' Devices.' . PHP_EOL; echo 'Runtime: ' . (microtime(true) - $ts) . ' secs' . PHP_EOL; } else { echo 'Please either add a range argument with \'-r <CIDR_RANGE>\' or define $config[\'nets\'] in your config.php' . PHP_EOL; exit(2); }
/** * convert an IP address into a hex value * * @param string $IP * @return string */ protected function convertIpToHex($host) { if (!isset($host) || empty($host) || !is_string($host)) { static::raiseError(__METHOD__ . '(), $host parameter is invalid!'); return false; } global $ms; $ipv4 = new Net_IPv4(); $parsed = $ipv4->parseAddress($host); // if CIDR contains no netmask or was unparsable, we assume /32 if (empty($parsed->netmask)) { $parsed->netmask = "255.255.255.255"; } if (!$ipv4->validateIP($parsed->ip)) { $ms->throwError(_("Incorrect IP address! Can not convert it to hex!")); } if (!$ipv4->validateNetmask($parsed->netmask)) { $ms->throwError(_("Incorrect Netmask! Can not convert it to hex!")); } if (($hex_host = $ipv4->atoh($parsed->ip)) == false) { $ms->throwError(_("Failed to convert " . $parsed->ip . " to hex!")); } if (($hex_subnet = $ipv4->atoh($parsed->netmask)) == false) { $ms->throwError(_("Failed to convert " . $parsed->netmask . " to hex!")); } return array('ip' => $hex_host, 'netmask' => $hex_subnet); }
echo "<script type='text/javascript'>window.listNetworkInterface=" . json_encode($listnetworkinterfaces) . ";</script>"; /**************************************************/ #speedandduplex $interfacerec->sql = "SELECT id_device_ifspeedduplex,device_ifspeedduplex FROM _device_ifspeedduplex"; $interfacerec->getRec(); $listifspeedduplex = $interfacerec->dbData; /**************************************************/ #label $interfacerec->sql = "\nSELECT \na.id_device_interfacelabel,\na.device_interfacelabel \nFROM _device_interfacelabel a\nWHERE NOT EXISTS \n(SELECT b.id_device_interfacelabel \nFROM _cfg_device_interface b \nWHERE a.id_device_interfacelabel=b.id_device_interfacelabel \nAND b.id_cfg_device=" . $_POST["id_cfg_device"] . " \nAND b.cfg_device_interface_enabled=1) AND id_device=" . $_POST["id_device"]; $interfacerec->getRec(); $listiflabel = $interfacerec->dbData; /**************************************************/ #netmask $listnetmask = array(); for ($i = 15; $i < 33; $i++) { $net = Net_IPv4::parseAddress("0.0.0.0/" . $i); $net->bitmask = $i; $netmask = $net->netmask; $listNetmask[] = array($i, $netmask . " / " . $i); } /**************************************************/ # Filterable Objects ## Network $gdbo = new ArcDb(); $gdbo->dbConStr = $globalDBCON; $gdbo->dbType = $globalDBTP; $gdbo->dbSchema = $globalDB; $gdbo->sql = "SELECT\nid_cfg_device_ip4netaddress,\nCONCAT(CAST(inet_ntoa(cfg_device_ip4netaddress) as CHAR),'/',CAST(cfg_device_ip4netaddress_nmbits as CHAR)) as Network\nFROM _cfg_device_ip4netaddress"; $gdbo->dbFilter = " WHERE id_cfg_device_netgroup="; $gdbo->type = "list"; $gdbo->id = "id_cfg_device_ip4netaddress";
$old_table[$entry['ifIndex']][$entry['ipv4_address']] = $entry; } // Process founded IPv4 addresses $valid[$ip_version] = array(); $check_networks = array(); if (count($ip_data)) { foreach ($ip_data as $ifIndex => $addresses) { if (!isset($cache['port_index'][$device_id][$ifIndex])) { continue; } // continue if ifIndex not found $port_id = $cache['port_index'][$device_id][$ifIndex]; foreach ($addresses as $ipv4_address => $entry) { $update_array = array(); $ipv4_mask = $entry['ipAdEntNetMask']; $addr = Net_IPv4::parseAddress($ipv4_address . '/' . $ipv4_mask); $ipv4_prefixlen = $addr->bitmask; $ipv4_network = $addr->network . '/' . $ipv4_prefixlen; $full_address = $ipv4_address . '/' . $ipv4_prefixlen; // First check networks $ipv4_network_id = dbFetchCell('SELECT `ipv4_network_id` FROM `ipv4_networks` WHERE `ipv4_network` = ?', array($ipv4_network)); if (empty($ipv4_network_id)) { $ipv4_network_id = dbInsert(array('ipv4_network' => $ipv4_network), 'ipv4_networks'); echo 'N'; } // Check IPs in DB if (isset($old_table[$ifIndex][$ipv4_address])) { foreach (array('ipv4_prefixlen', 'ipv4_network_id', 'port_id') as $param) { if ($old_table[$ifIndex][$ipv4_address][$param] != ${$param}) { $update_array[$param] = ${$param}; }
/** * Get first available IP address */ function getFirstAvailableIPAddress($subnetId) { global $database; /* get all ip addresses in subnet */ $query = 'SELECT `ip_addr` from `ipaddresses` where `subnetId` = "' . $subnetId . '" order by `ip_addr` ASC;'; /* execute */ try { $ipAddresses = $database->getArray($query); } catch (Exception $e) { $error = $e->getMessage(); print "<div class='alert alert-danger'>" . _('Error') . ": {$error}</div>"; return false; } /* get subnet */ $query = 'SELECT `subnet`,`mask` from `subnets` where `id` = "' . $subnetId . '";'; $subnet2 = $database->getArray($query); $subnet = $subnet2[0]['subnet']; $mask = $subnet2[0]['mask']; /* create array of IP addresses */ $ipaddressArray[] = $subnet; foreach ($ipAddresses as $ipaddress) { $ipaddressArray[] = $ipaddress['ip_addr']; } //get array size $size = sizeof($ipaddressArray); $curr = 0; //get type $type = IdentifyAddress($subnet); // IPv4 if ($type == "IPv4") { //if subnet is /32 if ($mask == "32") { if ($size == 1) { $firstAvailable = $ipaddressArray[0]; } else { $firstAvailable = false; } } elseif ($mask == "31") { if ($size == 1) { $firstAvailable = $ipaddressArray[0]; } elseif ($size == 2) { $delta = $ipaddressArray[1] - $ipaddressArray[0]; if ($delta == 1) { $firstAvailable = $ipaddressArray[0]; } else { $firstAvailable = gmp_strval(gmp_add($ipaddressArray[0], 1)); } } else { $firstAvailable = false; } } elseif ($size == 1) { $firstAvailable = gmp_strval(gmp_add($ipaddressArray[0], 1)); } else { //get first change -> delta > 1 for ($m = 1; $m <= $size - 1; $m++) { $delta = gmp_strval(gmp_sub($ipaddressArray[$m], $ipaddressArray[$m - 1])); //compare with previous if ($delta != 1) { $firstAvailable = gmp_strval(gmp_add($ipaddressArray[$m - 1], 1)); $m = $size; } else { $firstAvailable = gmp_strval(gmp_add($ipaddressArray[$m], 1)); } } //if bcast ignore! require_once 'PEAR/Net/IPv4.php'; $Net_IPv4 = new Net_IPv4(); $net = $Net_IPv4->parseAddress(transform2long($subnet) . "/" . $mask); if ($net->broadcast == transform2long($firstAvailable)) { $firstAvailable = false; } } } else { //if subnet is /128 if ($mask == "128" && $type == "IPv6") { if ($size == 1) { $firstAvailable = $ipaddressArray[0]; } else { $firstAvailable = false; } } elseif ($mask == "127" && $type == "IPv6") { if ($size == 1) { $firstAvailable = $ipaddressArray[0]; } elseif ($size == 2) { $delta = $ipaddressArray[1] - $ipaddressArray[0]; if ($delta == 1) { $firstAvailable = $ipaddressArray[0]; } else { $firstAvailable = gmp_strval(gmp_add($ipaddressArray[0], 1)); } } else { $firstAvailable = false; } } elseif ($size == 1) { $firstAvailable = gmp_strval($ipaddressArray[0]); } elseif ($subnet == $ipaddressArray[0]) { $firstAvailable = gmp_strval($subnet); } else { //get first change -> delta > 1 for ($m = 1; $m <= $size - 1; $m++) { $delta = gmp_strval(gmp_sub($ipaddressArray[$m], $ipaddressArray[$m - 1])); //compare with previous if ($delta != 1) { $firstAvailable = gmp_strval(gmp_add($ipaddressArray[$m - 1], 1)); $m = $size; } else { $firstAvailable = gmp_strval(gmp_add($ipaddressArray[$m], 1)); } } //if bcast ignore! $firstAvailable = gmp_strval(gmp_add($ipaddressArray[$size - 1], 1)); } } /* return first available IP address */ return $firstAvailable; }
/** * Returns all IPv4 subnet masks with different presentations * * @access public * @return void */ public function get_ipv4_masks() { # loop masks for ($mask = 30; $mask >= 8; $mask--) { // initialize $out[$mask] = new StdClass(); // fake cidr $this->initialize_pear_net_IPv4(); $net = Net_IPv4::parseAddress("10.0.0.0/{$mask}"); // set $out[$mask]->bitmask = $mask; // bitmask $out[$mask]->netmask = $net->netmask; // netmask $out[$mask]->host_bits = 32 - $mask; // host bits $out[$mask]->subnet_bits = 32 - $out[$mask]->host_bits; // network bits $out[$mask]->hosts = number_format($this->get_max_hosts($mask, "IPv4"), 0, ",", "."); // max hosts $out[$mask]->subnets = number_format(pow(2, $mask - 8), 0, ",", "."); // binary $parts = explode(".", $net->netmask); foreach ($parts as $k => $p) { $parts[$k] = str_pad(decbin($p), 8, 0); } $out[$mask]->binary = implode(".", $parts); } # return result return $out; }
$old_table[$entry['ifIndex']][$entry['ipv4_address']] = $entry; } // Process founded IPv4 addresses $valid[$ip_version] = array(); $check_networks = array(); if (count($ip_data)) { foreach ($ip_data as $ifIndex => $addresses) { if (!isset($cache['port_index'][$device_id][$ifIndex])) { continue; } // continue if ifIndex not found $port_id = $cache['port_index'][$device_id][$ifIndex]; foreach ($addresses as $ipv4_address => $entry) { $update_array = array(); $ipv4_prefix = $entry['ipAddressPrefix'] ? $entry['ipAddressPrefix'] : $entry['ipAdEntNetMask']; $addr = Net_IPv4::parseAddress($ipv4_address . '/' . $ipv4_prefix); $ipv4_prefixlen = $addr->bitmask; $ipv4_network = $addr->network . '/' . $ipv4_prefixlen; $full_address = $ipv4_address . '/' . $ipv4_prefixlen; // First check networks $ipv4_network_id = dbFetchCell('SELECT `ipv4_network_id` FROM `ipv4_networks` WHERE `ipv4_network` = ?', array($ipv4_network)); if (empty($ipv4_network_id)) { $ipv4_network_id = dbInsert(array('ipv4_network' => $ipv4_network), 'ipv4_networks'); echo 'N'; } // Check IPs in DB if (isset($old_table[$ifIndex][$ipv4_address])) { foreach (array('ipv4_prefixlen', 'ipv4_network_id', 'port_id') as $param) { if ($old_table[$ifIndex][$ipv4_address][$param] != ${$param}) { $update_array[$param] = ${$param}; }