private static function str_to_addr($ip) { if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { throw new Exception("'{$ip}' is not a valid IPv6 address."); } return current(unpack("a16", inet_pton($ip))); }
/** * Compares two IPv6 addresses. * In case a subnet is given, it checks if it contains the request IP. * * @author David Soria Parra <dsp at php dot net> * @see https://github.com/dsp/v6tools * * @param string $requestIp IPv6 address to check * @param string $ip IPv6 address or subnet in CIDR notation * * @return bool Whether the IP is valid * * @throws \RuntimeException When IPV6 support is not enabled */ public static function checkIp6($requestIp, $ip) { if (!(extension_loaded('sockets') && defined('AF_INET6') || @inet_pton('::1'))) { throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".'); } if (false !== strpos($ip, '/')) { list($address, $netmask) = explode('/', $ip, 2); if ($netmask < 1 || $netmask > 128) { return false; } } else { $address = $ip; $netmask = 128; } $bytesAddr = unpack("n*", inet_pton($address)); $bytesTest = unpack("n*", inet_pton($requestIp)); for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; $i++) { $left = $netmask - 16 * ($i - 1); $left = $left <= 16 ? $left : 16; $mask = ~(0xffff >> $left) & 0xffff; if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) { return false; } } return true; }
public function getLocation($ip, $full) { //Check if the given IP Adress is valid if (inet_pton($ip) !== false) { $jsonLocation = file_get_contents('http://85.214.151.129:8081/json/' . (string) $ip); //get the Contents of the server response (A JSON with all Location Data) //if an error occurs with file_get_contents it returns false //if there was no error with the request if ($jsonLocation !== false) { $arrLocation = json_decode($jsonLocation, true); //Convert the JSON string into an array //if the full location name was requested if ($full === true) { return $arrLocation['country_name']; //return the full location name } else { return $arrLocation['country_code']; //return the country code } } } else { //if the ip adress is not valid return null; //return null instead } }
/** * @param string ip * @throws \Exception */ public function __construct($ip) { if (!filter_var($ip, FILTER_VALIDATE_IP)) { throw new \Exception("Invalid IP address format"); } $this->in_addr = inet_pton($ip); }
/** * Returns the IP of the current client. * The IP address is validated against the security validator. In case of an invalid IP, IP_INVALID is returned. * @param bool Get the shorthand notation of an address. * @return string The ip address of the client. */ public static final function getClientIP($shortHand = true) { //validate the handle to the server variable $handle = self::getServerHandle(); $ip = self::IP_INVALID; switch (true) { case isset($handle['HTTP_CLIENT_IP']): //if there is a HTTP_CLIENT_IP variable, we parse this and use the first value in it. //this allows us to properly handle loadbalancers and cachers. $ar = explode(',', $handle['HTTP_CLIENT_IP']); $ip = trim(array_shift($ar)); break; case isset($handle['HTTP_X_FORWARDED_FOR']): //if there is a HTTP_X_FORWARDED_FOR variable, we parse this and use the first value in it. //this allows us to properly handle loadbalancers and cachers. $ar = explode(',', $handle['HTTP_X_FORWARDED_FOR']); $ip = trim(array_shift($ar)); break; case isset($handle['REMOTE_ADDR']): //if there is a REMOTE_ADDR variable, we parse this and use the first value in it. $ar = explode(',', $handle['REMOTE_ADDR']); $ip = trim(array_shift($ar)); break; } $val = new \System\Security\Validate(); if ($val->isIPAddress($ip, 'ip', true, true, false, false, true) == \System\Security\ValidateResult::VALIDATE_OK) { if ($shortHand) { return inet_ntop(inet_pton($ip)); } return $ip; } return self::IP_INVALID; }
/** * @see sfValidatorBase */ protected function doClean($value) { if (@inet_pton($value)) { return $value; } throw new sfValidatorError($this, 'invalid', array('value' => $value)); }
/** * Normalize an IP address or a beginning of it to an IPv6 address * * @param string $ip IP Address * @param bool $end Whether to make a partial address an "end of range" * address * * @return string|false Packed in_addr representation if successful, false * for invalid IP address */ public function normalizeIp($ip, $end = false) { // The check for AF_INET6 allows fallback to IPv4 only if necessary. // Hopefully that's not necessary. if (strpos($ip, ':') === false || !defined('AF_INET6')) { // IPv4 address // Append parts until complete $addr = explode('.', $ip); for ($i = count($addr); $i < 4; $i++) { $addr[] = $end ? 255 : 0; } // Get rid of leading zeros etc. $ip = implode('.', array_map('intval', $addr)); if (!defined('AF_INET6')) { return inet_pton($ip); } $ip = "::{$ip}"; } else { // IPv6 address // Expand :: with '0:' as many times as necessary for a complete address $count = substr_count($ip, ':'); if ($count < 8) { $ip = str_replace('::', ':' . str_repeat('0:', 8 - $count), $ip); } if ($ip[0] == ':') { $ip = "0{$ip}"; } // Append ':0' or ':ffff' to complete the address $count = substr_count($ip, ':'); if ($count < 7) { $ip .= str_repeat($end ? ':ffff' : ':0', 7 - $count); } } return inet_pton($ip); }
public function connect($url, $cb) { $u = $this->parseUrl($url); if (isset($u['user'])) { $this->user = $u['user']; } $this->url = $url; $this->scheme = $u['scheme']; $this->host = $u['host']; $this->port = $u['port']; if (isset($u['pass'])) { $this->password = $u['pass']; } if (isset($u['path'])) { $this->path = ltrim($u['path'], '/'); } if ($cb !== null) { $this->onConnected($cb); } $conn = $this; if ($this->port !== 0 && @inet_pton($this->host) === false) { // dirty condition check DNSClient::getInstance()->resolve($this->host, function ($real) use($conn) { if ($real === false) { Daemon::log(get_class($conn) . '->connectTo: enable to resolve hostname: ' . $conn->host); return; } $conn->hostReal = $real; $conn->connectTo($conn->hostReal, $conn->port); }); } else { $conn->hostReal = $conn->host; $conn->connectTo($conn->hostReal, $conn->port); } }
/** * Socket constructor * * @param string $host Remote hostname * @param int $port Remote port * @param string $debugHandler Function to call for error logging */ public function __construct($host = 'localhost', $port = 9090, $debugHandler = null) { $this->host_ = $host; $this->port_ = $port; $this->ipV6_ = strlen(@inet_pton($host)) == 16; $this->debugHandler_ = $debugHandler ?: 'error_log'; }
function start($user_id) { $data = array(); $data[":session_hash"] = sha1(rand()); // for now if (strstr($_SERVER['REMOTE_ADDR'], ":")) { // Remote address in in IPv6 notation $data[":session_ip_start"] = inet_pton($_SERVER['REMOTE_ADDR']); } else { // Remote address in IPv4 notation $data[":session_ip_start"] = inet_pton("::ffff:" . $_SERVER['REMOTE_ADDR']); } $data[":session_useragent"] = $_SERVER['HTTP_USER_AGENT']; $sth = $this->stone->pdo->prepare("INSERT INTO session \n (session_hash,session_ip_start,session_useragent)\n values (:session_hash,:session_ip_start,:session_useragent)"); if (!$sth->execute($data)) { //ERROR } // Set the cookie to the maximum 32 bit int value // to prevent year 2038 problems. setcookie("ItPhilManagerSession", $data[":session_hash"], 2147483647); $data = array(); $data[':session_id'] = $this->stone->pdo->lastInsertId(); $data[':user_id'] = $user_id; $sth = $this->stone->pdo->prepare("INSERT INTO link_session2user \n (session_id,user_id) \n VALUES (:session_id,:user_id)"); if (!$sth->execute($data)) { //ERROR } }
/** * Check if string is a valid IP address * * @param $name string to check * @return bool true if IP is valid */ function is_ip($name) { /*if(preg_match('/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/',$name)) return true; return false;*/ return @inet_pton($name) !== false; }
/** * check whether the expression matches an address * * @param AddressInterface $address * @return boolean */ public function matches(AddressInterface $address) { $lower = $this->lower->getExpanded(); $addr = $address->getExpanded(); // http://stackoverflow.com/questions/594112/matching-an-ip-to-a-cidr-mask-in-php5 if ($address instanceof IPv4 && $this->lower instanceof IPv4) { $addr = ip2long($addr); $lower = ip2long($lower); $netmask = -1 << 32 - $this->netmask & ip2long('255.255.255.255'); $lower &= $netmask; return ($addr & $netmask) == $lower; } elseif ($address instanceof IPv6 && $this->lower instanceof IPv6) { $lower = unpack('n*', inet_pton($lower)); $addr = unpack('n*', inet_pton($addr)); for ($i = 1; $i <= ceil($this->netmask / 16); $i++) { $left = $this->netmask - 16 * ($i - 1); $left = $left <= 16 ? $left : 16; $mask = ~(0xffff >> $left) & 0xffff; if (($addr[$i] & $mask) != ($lower[$i] & $mask)) { return false; } } return true; } throw new \LogicException('Can only compare IPs of the same version.'); }
public function getBinary() { if ($this->_binary === null) { $this->_binary = inet_pton($this->_value); } return $this->_binary; }
static function reverseIPv6($ip) { $addr = inet_pton($ip); $unpack = unpack('H*hex', $addr); $hex = $unpack['hex']; return implode('.', array_reverse(str_split($hex))); }
function get_cache($host, $value) { global $dev_cache; if (!isset($dev_cache[$host][$value])) { switch ($value) { case 'device_id': // Try by hostname $ip = inet_pton($host); if (inet_ntop($ip) === false) { $dev_cache[$host]['device_id'] = dbFetchCell('SELECT `device_id` FROM devices WHERE `hostname` = ? OR `sysName` = ?', array($host, $host)); } else { $dev_cache[$host]['device_id'] = dbFetchCell('SELECT `device_id` FROM devices WHERE `hostname` = ? OR `sysName` = ? OR `ip` = ?', array($host, $host, $ip)); } // If failed, try by IP if (!is_numeric($dev_cache[$host]['device_id'])) { $dev_cache[$host]['device_id'] = dbFetchCell('SELECT `device_id` FROM `ipv4_addresses` AS A, `ports` AS I WHERE A.ipv4_address = ? AND I.port_id = A.port_id', array($host)); } break; case 'os': $dev_cache[$host]['os'] = dbFetchCell('SELECT `os` FROM devices WHERE `device_id` = ?', array(get_cache($host, 'device_id'))); break; case 'version': $dev_cache[$host]['version'] = dbFetchCell('SELECT `version` FROM devices WHERE `device_id`= ?', array(get_cache($host, 'device_id'))); break; default: return null; } //end switch } //end if return $dev_cache[$host][$value]; }
/** * Logs an action. * * @param string $action * @param App\Board|String $board * @param Array $data * @return App\Log */ public function log($action, $board = null, $data = null) { $board_uri = null; $action_details = null; if ($board instanceof \App\Board) { $board_uri = $board->board_uri; $action_details = $data; } else { if ($board instanceof \App\Post) { $board_uri = $board->board_uri; $action_details = $data; } else { if (is_string($board)) { $board_uri = $board; $action_details = $data; } else { if (is_array($board) && is_null($data)) { $board_uri = null; $action_details = $board; } } } } if (!is_null($action_details) && !is_array($action_details)) { $action_details = [$action_details]; } if (!is_null($action_details)) { $action_details = json_encode($action_details); } $log = new Log(['action_name' => $action, 'action_details' => $action_details, 'user_id' => $this->user->isAnonymous() ? null : $this->user->user_id, 'user_ip' => inet_pton(Request::getClientIp()), 'board_uri' => $board_uri]); return $log->save(); }
public static function get_ip() { static $ip; if (!empty($ip)) { return $ip; } $ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : $_ENV['REMOTE_ADDR']; $ips = array(); if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != 'unknown') { $ips = explode(', ', $_SERVER['HTTP_X_FORWARDED_FOR']); } if (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != 'unknown') { $ips[] = $_SERVER['HTTP_CLIENT_IP']; } for ($i = 0; $i < count($ips); $i++) { if ($tmp = FILTER::ipv4($ips[$i])) { $ip = $tmp; break; } else { if ($tmp = FILTER::ipv6($ips[$i])) { $ip = $tmp; break; } } } $ip = inet_pton($ip); return $ip; }
/** * Convert an IP address from presentation to decimal(39,0) format suitable for storage in MySQL * * @param string $ip_address An IP address in IPv4, IPv6 or decimal notation * @return string The IP address in decimal notation */ public function ip2dec($ip_address) { if (is_null($ip_address) === true) { return null; } $ip_address = trim($ip_address); // IPv4 address if (strpos($ip_address, ':') === false && strpos($ip_address, '.') !== false) { $ip_address = '::' . $ip_address; } // IPv6 address if (strpos($ip_address, ':') !== false) { $network = inet_pton($ip_address); $parts = unpack('N*', $network); foreach ($parts as &$part) { if ($part < 0) { $part = bcadd((string) $part, '4294967296'); } if (!is_string($part)) { $part = (string) $part; } } $decimal = $parts[4]; $decimal = bcadd($decimal, bcmul($parts[3], '4294967296')); $decimal = bcadd($decimal, bcmul($parts[2], '18446744073709551616')); $decimal = bcadd($decimal, bcmul($parts[1], '79228162514264337593543950336')); return $decimal; } // Decimal address return $ip_address; }
function is_mptcp() { // Convert IP to packed in_addr form $ip = inet_pton($_SERVER['REMOTE_ADDR']); // Convert port to hex $port_hex = strtoupper(dechex($_SERVER['REMOTE_PORT'])); // Split IP into array $ip_hex = ''; $ip_array = str_split($ip); // IPv4 conversion to hex if (count($ip_array) === 4) { // Iterate all characters, convert to hex foreach ($ip_array as $c) { $ip_hex = sprintf("%s%s", char2hex($c), $ip_hex); } } else { // Iterate all characters, convert to hex for ($i = 1; $i <= 4; $i++) { for ($j = 4 * $i - 1; $j >= ($i - 1) * 4; $j--) { $ip_hex = sprintf("%s%s", $ip_hex, char2hex($ip_array[$j])); } } } // Convert to uppercase $ip_hex = strtoupper($ip_hex); // Return if you're connected via MPTCP! return strpos(shell_exec("cat /proc/net/mptcp"), $ip_hex . ':' . $port_hex) ? true : false; }
public function __construct($uri) { $uri = (string) $uri; if (!($parts = $this->parse($uri))) { throw new \DomainException('Invalid URI specified at ' . get_class($this) . '::__construct Argument 1'); } $this->uri = $uri; foreach ($parts as $key => $value) { $this->{$key} = $value; } // http://www.apps.ietf.org/rfc/rfc3986.html#sec-3.1 // "schemes are case-insensitive" $this->scheme = strtolower($this->scheme); // http://www.apps.ietf.org/rfc/rfc3986.html#sec-3.2.2 // "Although host is case-insensitive, producers and normalizers should use lowercase for // registered names and hexadecimal addresses for the sake of uniformity" $this->host = strtolower($this->host); if ($this->port && $this->scheme) { $this->normalizeDefaultPort(); } $ip = @inet_pton($this->host); if (isset($ip[5])) { $this->isIpV6 = true; } elseif ($ip) { $this->isIpv4 = true; } $this->parseQueryParameters(); if ($this->fragment) { $this->fragment = rawurldecode($this->fragment); $this->fragment = rawurlencode($this->fragment); } }
/** * Matches a CIDR range pattern against an IP * * @param string $ip The IP to match * @param string $range The CIDR range pattern to match against * @return boolean TRUE if the pattern matched, FALSE otherwise */ protected function cidrMatch($ip, $range) { if (strpos($range, '/') === false) { $bits = null; $subnet = $range; } else { list($subnet, $bits) = explode('/', $range); } $ip = inet_pton($ip); $subnet = inet_pton($subnet); if ($ip === false || $subnet === false) { return false; } if (strlen($ip) > strlen($subnet)) { $subnet = str_pad($subnet, strlen($ip), chr(0), STR_PAD_LEFT); } elseif (strlen($subnet) > strlen($ip)) { $ip = str_pad($ip, strlen($subnet), chr(0), STR_PAD_LEFT); } if ($bits === null) { return $ip === $subnet; } else { for ($i = 0; $i < strlen($ip); $i++) { $mask = 0; if ($bits > 0) { $mask = $bits >= 8 ? 255 : 256 - (1 << 8 - $bits); $bits -= 8; } if ((ord($ip[$i]) & $mask) !== (ord($subnet[$i]) & $mask)) { return false; } } } return true; }
/** * @param string $ip * @throws \InvalidArgumentException */ public function __construct($ip) { if (!@inet_pton($ip)) { throw new \InvalidArgumentException("IP '{$ip}' is not a valid address"); } $this->ip = $ip; }
public function __construct($host = "localhost", $port = 9090, $debugHandler = null) { $this->host_ = $host; $this->port_ = $port; $this->ipV6_ = \hacklib_equals(strlen(inet_pton($host)), 16); $this->debugHandler_ = \hacklib_cast_as_boolean($debugHandler) ?: fun("error_log"); }
/** * nv_getCountry_from_file() * * @param string $ip * @return */ function nv_getCountry_from_file($ip) { global $countries; if (preg_match('/^([0-9]{1,3}+)\\.([0-9]{1,3}+)\\.([0-9]{1,3}+)\\.([0-9]{1,3}+)$/', $ip, $numbers)) { $code = $numbers[1] * 16777216 + $numbers[2] * 65536 + $numbers[3] * 256 + $numbers[4]; $ranges = array(); include NV_ROOTDIR . '/' . NV_IP_DIR . '/' . $numbers[1] . '.php'; if (!empty($ranges)) { foreach ($ranges as $key => $value) { if ($key <= $code and $value[0] >= $code) { return $value[1]; } } } } else { $numbers = explode(':', $ip); if (file_exists(NV_ROOTDIR . '/' . NV_IP_DIR . '6/' . $numbers[0] . '.php')) { $ip = inet_pton($ip); $binaryip = inet_to_bits($ip); $ranges = array(); include NV_ROOTDIR . '/' . NV_IP_DIR . '6/' . $numbers[0] . '.php'; foreach ($ranges as $cidrnet => $country) { list($net, $maskbits) = explode('/', $cidrnet); $net = inet_pton($net); $binarynet = inet_to_bits($net); $ip_net_bits = substr($binaryip, 0, $maskbits); $net_bits = substr($binarynet, 0, $maskbits); if ($ip_net_bits === $net_bits) { return $country; } } } } return 'ZZ'; }
/** * @dataProvider validAddresses */ public function testConvertToNumeric($ip, $compressed, $dec) { $instance = new IPv6($ip); $array = unpack('H*', inet_pton($compressed)); $this->assertEquals(ltrim($array[1], 0), $instance->numeric(16), "Base 16 of {$compressed}"); $this->assertEquals($dec, $instance->numeric(10), "Base 10 of {$compressed}"); }
/** * Update user rate of a reference item * * @access public * @param string $gadget Gadget name * @param string $action Action name * @param int $reference Reference * @param int $item Rating item * @param int $rate User rate(if null user old rate will be removed) * @return mixed Rate value or Jaws_Error on failure */ function UpdateUserRating($gadget, $action, $reference, $item = 0, $rate = null) { $objORM = Jaws_ORM::getInstance(); // fetch reference item from parent table(rating) $rid = $objORM->table('rating')->upsert(array('gadget' => $gadget, 'action' => $action, 'reference' => $reference, 'item' => $item))->where('gadget', $gadget)->and()->where('action', $action)->and()->where('reference', $reference)->and()->where('item', $item)->exec(); if (Jaws_Error::IsError($rid)) { return $rid; } // insert/update user rate $uip = bin2hex(inet_pton($_SERVER['REMOTE_ADDR'])); $objORM->beginTransaction(); if (is_null($rate)) { // delete user rate $result = $objORM->table('rating_details')->delete()->where('rid', $rid)->and()->where('uip', $uip)->exec(); } else { // update/insert user rate $result = $objORM->table('rating_details')->upsert(array('rid' => $rid, 'uip' => $uip, 'rate' => (int) $rate))->where('rid', $rid)->and()->where('uip', $uip)->exec(); } if (Jaws_Error::IsError($result)) { return $result; } // update rating statistics $result = $objORM->table('rating')->update(array('rates_count' => Jaws_ORM::getInstance()->table('rating_details')->select('count(id)')->where('rid', $rid), 'rates_sum' => Jaws_ORM::getInstance()->table('rating_details')->select('sum(rate)')->where('rid', $rid), 'rates_avg' => Jaws_ORM::getInstance()->table('rating_details')->select('avg(rate)')->where('rid', $rid)))->where('id', $rid)->exec(); if (Jaws_Error::IsError($result)) { return $result; } //commit transaction $objORM->commit(); return true; }
private function IPv6Match($address, $subnetAddress, $subnetMask) { $subnet = inet_pton($subnetAddress); $addr = inet_pton($address); $binMask = $this->IPv6MaskToByteArray($subnetMask); return ($addr & $binMask) == $subnet; }
public static function type(&$ip, &$type, &$ip2 = NULL) { if (isset(self::$ip_cache[$ip])) { list($ip, $type, $addr, $ip2) = self::$ip_cache[$ip]; return $addr; } $ip2 = false; $addr = @inet_pton($ip); if (!$addr) { $type = false; return false; } $len = strlen($addr); if ($len === 4) { $type = self::IP4; } elseif ($len === 16) { $first12 = $addr[0] . $addr[1] . $addr[2] . $addr[3] . $addr[4] . $addr[5] . $addr[6] . $addr[7] . $addr[8] . $addr[9] . $addr[10] . $addr[11]; $last4 = $addr[12] . $addr[13] . $addr[14] . $addr[15]; switch ($first12) { case "ÿÿ": case "ÿÿ": case "dÿ›": $addr = $last4; $type = self::IP4; break; case "": if (!_string::bincmp($addr, "", 127)) { $type = self::IP6; } else { $addr = $last4; $type = self::IP4; } break; default: $type = self::IP6; if ($addr[0] . $addr[1] === " ") { // 6to4 $ip4 = $addr[2] . $addr[3] . $addr[4] . $addr[5]; $ip4 = @inet_ntop($ip4); if ($ip4) { $ip2 = $ip4; } } elseif ($addr[0] . $addr[1] . $addr[2] . $addr[3] === " ") { // Teredo $ip4 = $last4; $ip4 = @unpack('N', $ip4); if ($ip4) { $ip2 = long2ip(~$ip4[1]); } // Flip the bits } break; } } else { $type = false; } self::$ip_cache[$ip] = array(@inet_ntop($addr), $type, $addr, $ip2); $ip = self::$ip_cache[$ip][0]; return $addr; }
function _prepare_ip($ip_address) { if ($this->conn->databaseType === 'postgre' || $this->conn->databaseType === 'sqlsrv' || $this->conn->databaseType === 'mssql') { return $ip_address; } else { return inet_pton($ip_address); } }
/** * Expands an IPv6 address to its full, non-shorthand representation. * * E.g. 2001:db8:9a::42 -> 2001:0db8:009a:0000:0000:0000:0000:0042 * * @param string $ip IPv6 address * @throws \InvalidArgumentException * * @return string */ public static function expandIpv6($ip) { if (!Validator::validateIpv6Address($ip)) { throw new \InvalidArgumentException(sprintf('"%s" is not a valid IPv6 address.', $ip)); } $hex = unpack('H*hex', inet_pton($ip)); return substr(preg_replace('/([A-f0-9]{4})/', '$1:', $hex['hex']), 0, -1); }