根据IP获取地址信息

参考错误
Array (
[status] => 2
[message] => Request Parameter Error:ak required/参数必须
[uid] => [sk] =>
[logformat] =>
[ak] =>
)

@param string $ip
@return array
@link http://developer.baidu.com/map/ip-location-api.htm
18404
public function getIpInfo($ip)
    {
        $response = $this->http([
            'url' => 'http://api.map.baidu.com/location/ip',
            'referer' => true,
            'dataType' => 'json',
            'timeout' => 30000,
            'throwException' => false,
            'data' => [
                'ak' => $this->accessKey,
                'ip' => $ip,
            ],
        ]);

        if ($response['status'] !== 0) {
            $this->logger->warning('获取IP信息失败', [
                'ip' => $ip,
                'res' => $response->getResponse(),
            ]);
        }

        // 重新构造数据结构,和其他接口保持一致
        $detail = $response['content']['address_detail'];
        $parts = explode('|', $response['address']);

        return [
            'code' => $response['status'] === 0 ? 1 : -$response['status'],
            'province' => $detail['province'],
            'city' => $detail['city'],
            'district' => $detail['district'],
            'street' => $detail['street'],
            'address' => $detail['street'] . $detail['street_number'],
            'point' => $response['content']['point'],
            'isp' => $parts[4],
        ];
    }
681462
public static function clientArea($ip = '')
    {
        if (!$ip) {
            $ip = self::clientIp();
        }

        return json_decode(file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip), true);
    }
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;
	}
1182680
public function ip2longV6($ip)
    {
        if (substr_count($ip, '::')) {
            $ip = str_replace('::', str_repeat(':0000', 8 - substr_count($ip, ':')) . ':', $ip);
        }
        $ip   = explode(':', $ip);
        $r_ip = '';
        foreach ($ip as $v) {
            $r_ip .= str_pad(base_convert($v, 16, 2), 16, 0, STR_PAD_LEFT);
        }

        return base_convert($r_ip, 2, 10);
    }
1148550
public static function getIp()
    {
        if (isset($_SERVER)) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                /* 取X-Forwarded-For中第x个非unknown的有效IP字符? */
                foreach ($arr as $ip) {
                    $ip = trim($ip);
                    if ($ip != 'unknown') {
                        $realIp = $ip;
                        break;
                    }
                }
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $realIp = $_SERVER['HTTP_CLIENT_IP'];
            } else {
                if (isset($_SERVER['REMOTE_ADDR'])) {
                    $realIp = $_SERVER['REMOTE_ADDR'];
                } else {
                    $realIp = '0.0.0.0';
                }
            }
        } else {
            if (getenv('HTTP_X_FORWARDED_FOR')) {
                $realIp = getenv('HTTP_X_FORWARDED_FOR');
            } elseif (getenv('HTTP_CLIENT_IP')) {
                $realIp = getenv('HTTP_CLIENT_IP');
            } else {
                $realIp = getenv('REMOTE_ADDR');
            }
        }

        if (isset($realIp)) {
            if (preg_match('/[\d\.]{7,15}/', $realIp, $onlineIp)) {
                $realIp = $onlineIp[0];
            }
        }

        return isset($realIp) ? $realIp : '0.0.0.0';
    }
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;
	}
777197
public function ipInfo($ip = '')
    {
        if (empty($ip)) {
            $ip = $this->getIpAddress();
        }
        try {
            $curl = new \Curl\Curl();
            $curl->get('http://ip-api.com/json/' . $ip);
            $response = $curl->error ? "cURL Error: " . $curl->errorMessage : $curl->response;

            return $response;
        }
        catch (\Exception $e) {
            $message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();

            return $message;
        }
    }
647747
private function find($ip = null)
    {
        // If IP not set, user remote IP
        $ip = $ip ?: $this->remote_ip;

        // Check cache for location
        if ($this->config('cache', 'none') !== 'none' && $location = $this->getCache()->get($ip)) {
            $location->cached = true;

            return $location;
        }

        // Check if the ip is not local or empty
        if ($this->isValid($ip)) {
            try {
                // Find location
                $location = $this->getService()->locate($ip);

                // Set currency if not already set by the service
                if (!$location->currency) {
                    $location->currency = $this->getCurrency($location->iso_code);
                }

                // Set default
                $location->default = false;

                return $location;
            }
            catch (\Exception $e) {
                if ($this->config('log_failures', true) === true) {
                    $log = new Logger('geoip');
                    $log->pushHandler(new StreamHandler(storage_path('logs/geoip.log'), Logger::ERROR));
                    $log->addError($e);
                }
            }
        }

        return $this->getService()->hydrate($this->default_location);
    }
1192384
private function ip_is_private($ip)
    {
        $privateAddresses = [ '10.0.0.0|10.255.255.255', '172.16.0.0|172.31.255.255', '192.168.0.0|192.168.255.255', '169.254.0.0|169.254.255.255', '127.0.0.0|127.255.255.255' ];
        $long_ip = ip2long($ip);
        if($long_ip != -1)
        {
            foreach($privateAddresses as $pri_addr)
            {
                list($start, $end) = explode('|', $pri_addr);
                // IF IS PRIVATE
                if($long_ip >= ip2long($start) && $long_ip <= ip2long($end))
                {
                        return true;
                }
            }
        }
        return false;
    }
759106
public static function IPv4toInteger($ip)
    {
        $ips = explode('.', $ip);
        $integer = 0;
        for ($i = 0; $i < 4; $i++)
        {
            $ips[$i] = intval($ips[$i] % 256);
            $ips[$i] = pow(256, 3 - $i) * intval($ips[$i]);
            $integer += $ips[$i];
        }
        return $integer;
    }
437277
public static function check_ipv6($ip)
	{
		$ip = self::uncompress($ip);
		list($ipv6, $ipv4) = self::split_v6_v4($ip);
		$ipv6 = explode(':', $ipv6);
		$ipv4 = explode('.', $ipv4);
		if (count($ipv6) === 8 && count($ipv4) === 1 || count($ipv6) === 6 && count($ipv4) === 4)
		{
			foreach ($ipv6 as $ipv6_part)
			{
				// The section can't be empty
				if ($ipv6_part === '')
					return false;

				// Nor can it be over four characters
				if (strlen($ipv6_part) > 4)
					return false;

				// Remove leading zeros (this is safe because of the above)
				$ipv6_part = ltrim($ipv6_part, '0');
				if ($ipv6_part === '')
					$ipv6_part = '0';

				// Check the value is valid
				$value = hexdec($ipv6_part);
				if (dechex($value) !== strtolower($ipv6_part) || $value < 0 || $value > 0xFFFF)
					return false;
			}
			if (count($ipv4) === 4)
			{
				foreach ($ipv4 as $ipv4_part)
				{
					$value = (int) $ipv4_part;
					if ((string) $value !== $ipv4_part || $value < 0 || $value > 0xFF)
						return false;
				}
			}
			return true;
		}
		else
		{
			return false;
		}
	}
467693
public static function compressIp($ip)
    {
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            return current(unpack('A4', inet_pton($ip)));
        }
        elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            return current(unpack('A16', inet_pton($ip)));
        }
        return false;
    }
980421
public function getRaw($ip)
    {
        try {
            return json_decode($this->guzzle->get($this->getUrl($ip))->getBody(), true);
        } catch (RequestException $e) {
            // ignore
        }

        return [];
    }
73235
private function ip2bin($ip)
    {
        if ($this->getIpVersion($ip) === 4) {
            return str_pad(base_convert(ip2long($ip), 10, 2), static::IPV4_ADDRESS_LENGTH, '0', STR_PAD_LEFT);
        } else {
            $unpack = unpack('A16', inet_pton($ip));
            $binStr = array_shift($unpack);
            $bytes = static::IPV6_ADDRESS_LENGTH / 8; // 128 bit / 8 = 16 bytes
            $result = '';
            while ($bytes-- > 0) {
                $result = sprintf('%08b', isset($binStr[$bytes]) ? ord($binStr[$bytes]) : '0') . $result;
            }
            return $result;
        }
    }
493558
public static function isLocal(string $ip = null)
    {
        if (is_null($ip)) {
            $ip = self::get();
        }

        if (stripos($ip, '127.') !== false) {
            return true;
        }

        return !(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) == $ip);
    }
306082
public static function getSubnet($ip, $prefix = 64)
    {
        if (!filter_var($ip, FILTER_VALIDATE_IP)) {
            throw new \InvalidArgumentException('Invalid IP: ' . $ip);
        }

        // Packed representation of IP
        $ip = inet_pton($ip);

        // Maximum netmask length = same as packed address
        $len = 8*strlen($ip);
        if ($prefix > $len) $prefix = $len;

        $mask  = str_repeat('f', $prefix>>2);

        switch($prefix & 3)
        {
            case 3: $mask .= 'e'; break;
            case 2: $mask .= 'c'; break;
            case 1: $mask .= '8'; break;
        }
        $mask = str_pad($mask, $len>>2, '0');

        // Packed representation of netmask
        $mask = pack('H*', $mask);
        // Bitwise - Take all bits that are both 1 to generate subnet
        $subnet = inet_ntop($ip & $mask);

        return $subnet;
    }
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;
    }