Return geolocation data based on specified/auto-detected IP address
@return array|FALSE
@param $ip string
501967
function location($ip=NULL) {
		$fw=Base::instance();
		$web=Web::instance();
		if (!$ip)
			$ip=$fw->get('IP');
		$public=filter_var($ip,FILTER_VALIDATE_IP,
			FILTER_FLAG_IPV4|FILTER_FLAG_IPV6|
			FILTER_FLAG_NO_RES_RANGE|FILTER_FLAG_NO_PRIV_RANGE);
		if (function_exists('geoip_db_avail') &&
			geoip_db_avail(GEOIP_CITY_EDITION_REV1) &&
			$out=@geoip_record_by_name($ip)) {
			$out['request']=$ip;
			$out['region_code']=$out['region'];
			$out['region_name']=geoip_region_name_by_code(
				$out['country_code'],$out['region']);
			unset($out['country_code3'],$out['region'],$out['postal_code']);
			return $out;
		}
		if (($req=$web->request('http://www.geoplugin.net/json.gp'.
			($public?('?ip='.$ip):''))) &&
			$data=json_decode($req['body'],TRUE)) {
			$out=array();
			foreach ($data as $key=>$val)
				if (!strpos($key,'currency') && $key!=='geoplugin_status'
					&& $key!=='geoplugin_region')
					$out[$fw->snakecase(substr($key, 10))]=$val;
			return $out;
		}
		return FALSE;
	}
792383
public function getRawIpAddress($convertToInteger = FALSE)
    {
        $ip_keys = Repository\DataRepository::getData('ip_address_server');
        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === TRUE) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip);
                    if ($this->ipValidate($ip)) {
                        if ($convertToInteger === TRUE) {
                            $result = ip2long($ip);

                            return $result;
                        }

                        return $ip;
                    }
                }
            }
        }

        return FALSE;
    }
637517
public static function find($ip)
    {
        if (empty($ip) === true) {
            return 'N/A';
        }

        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6) === FALSE) {
            throw new \InvalidArgumentException("The value \"$ip\" is not a valid IP address.");
        }

        $nip = gethostbyname($ip);
        if (isset(self::$cached[$nip]) === true) {
            return self::$cached[$nip];
        }

        try {
            $reader = self::init();
            $node   = $reader->findNode($ip);

            if ($node > 0) {
                $data               = $reader->resolve($node);
                $values             = explode("\t", $data);
                $location           = array_slice($values, $reader->meta['languages']['CN'], count($reader->meta['fields']));
                $location[]         = '';
                $locationCode       = self::getLocationCode($location);
                $location[]         = $locationCode;
                self::$cached[$nip] = $location;

                return self::$cached[$nip];
            }
        } catch (\Exception $e) {
            return $e->getMessage();
        }

        return 'N/A';
    }
584847
public function getHostsForIp($ip)
    {
        // check binary representation of IP to avoid string case and short notation
        $ip = @inet_pton($ip);
        if ($ip === false) {
            return array();
        }

        $names = array();
        foreach (preg_split('/\r?\n/', $this->contents) as $line) {
            $parts = preg_split('/\s+/', $line, null, PREG_SPLIT_NO_EMPTY);
            $addr = array_shift($parts);

            // remove IPv6 zone ID (`fe80::1%lo0` => `fe80:1`)
            if (strpos($addr, ':') !== false && ($pos = strpos($addr, '%')) !== false) {
                $addr = substr($addr, 0, $pos);
            }

            if (@inet_pton($addr) === $ip) {
                foreach ($parts as $part) {
                    $names[] = $part;
                }
            }
        }

        return $names;
    }
314276
public static function checkIp(string $ip, array $Ips = null): bool {
		// 内网ip列表
		$ruleIps = $Ips ?? [
				['10.0.0.0', '10.255.255.255'],
				['172.16.0.0', '172.31.255.255'],
				['192.168.0.0', '192.168.255.255'],
				['127.0.0.0', '127.255.255.255']
			];
		$ipInt   = ip2long(trim($ip));
		if ($ipInt === false)
			throw new InvalidArgumentException("Invalid IP[$ip].");
		foreach ($ruleIps as $rule) {
			if ($ipInt >= ip2long(reset($rule)) && $ipInt <= ip2long(end($rule))) {
				return true;
			}
		}
		return false;
	}
980421
public function getRaw($ip)
    {
        try {
            return json_decode($this->guzzle->get($this->getUrl($ip))->getBody(), true);
        } catch (RequestException $e) {
            // ignore
        }

        return [];
    }
1365053
protected function validateIp($ip)
    {
        $filter = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
        return filter_var($ip, FILTER_VALIDATE_IP, $filter);
    }
814624
protected function getData()
    {
        $ip = $this->getIp();
        $this->setIp($ip);

        // check ip in memory
        $data = array_get($this->store, $ip);

        if (! $data) {
            try {
                $data = $this->getDriver()->get($ip);
            } catch (\Exception $e) {
                throw new GeoIPException('Failed to get geoip data', 0, $e);
            }

            // cache ip data in memory
            $this->store[$ip] = $data;
        }

        return $data;
    }
61005
public function locate($ip)
    {
        // Get data from client
        $data = $this->client->get($ip);

        // Verify server response
        if ($this->client->getErrors() !== null || empty($data[0])) {
            throw new Exception('Request failed (' . $this->client->getErrors() . ')');
        }

        $json = json_decode($data[0], true);

        return $this->hydrate([
            'ip' => $ip,
            'iso_code' => $json['country_code'],
            'country' => $json['continent_name'],
            'city' => $json['city'],
            'state' => $json['region_code'],
            'state_name' => $json['region'],
            'postal_code' => $json['postal'],
            'lat' => $json['latitude'],
            'lon' => $json['longitude'],
            'timezone' => Arr::get($json, 'time_zone.name'),
            'continent' => Arr::get($json, 'continent_code'),
            'currency' => Arr::get($json, 'currency.code'),
        ]);
    }
538462
private function isAllowed($ip) {
        // Look for a wildcard
        if (in_array('*', $this->params['allow'])) {
            // There is a wildcard in the list, all IP's are allowed
            return true;
        }

        // Remove IP's which is not of the same type as $ip before matching
        if ($this->isIPv6($ip)) {
            $list = array_filter($this->params['allow'], [$this, 'isIPv6']);
        } else {
            $list = array_filter($this->params['allow'], [$this, 'isIPv4']);
        }

        foreach ($list as $range) {
            if ((strpos($range, '/') !== false && $this->cidrMatch($ip, $range)) || $ip === $range) {
                return true;
            }
        }

        return false;
    }
872030
public static String getLocationByIp(String ip) throws IOException, XPathExpressionException,
            ParserConfigurationException {
        return evaluate(ValueConsts.IP_REGION_XPATH, getHtmlFromUrl("http://ip.chinaz.com/" + ip));
    }
1109998
public static function is_iplocation($ip, $location)
	{
		$iplocation = false;
		if ($ip && $location)
		{
			if (!($gdb = self::getGeoDBO()))
			{
				return $iplocation;
			}

			$sql = "SELECT COUNT(*) FROM iplocation WHERE ipfrom <= INET_ATON(" . $gdb->quote($ip) . ") AND ipto >= INET_ATON(" . $gdb->quote($ip) . ") AND LOWER(location) = LOWER(" . $gdb->quote($location) . ")";
			$gdb->setQuery($sql);
			$c = $gdb->loadResult();
			if ($c > 0)
			{
				$iplocation = true;
			}
		}
		return $iplocation;
	}
453298
public static function ipToNetAddress($ip)
	{
		$parts = explode('.', $ip);
		$address = '1#';

		foreach ($parts as $int)
		{
			$tmp = dechex($int);

			if (strlen($tmp) != 2)
			{
				$tmp = '0' . $tmp;
			}

			$address .= '\\' . $tmp;
		}

		return $address;
	}
383923
public static function getClientLocation()
    {
        $result = false;
        $ip_data = @json_decode(self::curl('http://www.geoplugin.net/json.gp?ip='.self::getClientIP()));

        if (isset($ip_data) && $ip_data->geoplugin_countryName != null) {
            $result = $ip_data->geoplugin_city.', '.$ip_data->geoplugin_countryCode;
        }

        return $result;
    }
953733
public function match( $ip ) {
		$raw = AtEase::quietCall( 'inet_pton', $ip );
		if ( $raw === false ) {
			return false;
		}

		$rawOrd = array_map( 'ord', str_split( $raw ) );
		if ( count( $rawOrd ) == 4 ) {
			$node =& $this->root4;
		} else {
			$node =& $this->root6;
		}

		$curBit = 0;
		while ( $node !== true && $node !== false ) {
			if ( isset( $node['comp'] ) ) {
				// compressed node, matches 1 whole byte on a byte boundary
				if ( $rawOrd[$curBit >> 3] != $node['comp'] ) {
					return false;
				}
				$curBit += 8;
				$node =& $node['next'];
			} else {
				// uncompressed node, walk in the correct direction for the current bit-value
				$maskShift = 7 - ( $curBit & 7 );
				$node =& $node[( $rawOrd[$curBit >> 3] & ( 1 << $maskShift ) ) >> $maskShift];
				++$curBit;
			}
		}

		return $node;
	}
1079492
protected function getUrl($ip)
    {
        // default to free service
        // free service does not support https
        $baseUrl = 'http://ip-api.com/json/';
        $key = '';

        // if key is set change to pro service
        if (array_get($this->config, 'key', false)) {
            $baseUrl = 'https://pro.ip-api.com/json/';
            $key = array_get($this->config, 'key');
        }

        return $baseUrl.$ip.(($key) ? '?key='.$key : '');
    }
198878
public function getIpAdress()
    {
        $ip_keys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'];
        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip);
                    if ($this->validateIp($ip)) {
                        return $ip;
                    }
                }
            }
        }

        return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false;
    }