Function ipInfo

@author: 713uk13m <dev@nguyenanhung.com>
@time  : 10/18/18 11:39

@param string $ip

@return string
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;
        }
    }
890523
public static function toLong(string $ip = null)
    {
        if (is_null($ip)) {
            $ip = self::get();
        }

        return ip2long($ip);
    }
1199196
public static function ip2long($ip)
    {
        $long = -1;
        if (self::isValidv6($ip)) {
            if (!function_exists('bcadd')) {
                throw new \RuntimeException('BCMATH extension not installed!');
            }

            $ip_n = inet_pton($ip);
            $bin = '';
            for ($bit = strlen($ip_n) - 1; $bit >= 0; $bit--) {
                $bin = sprintf('%08b', ord($ip_n[$bit])) . $bin;
            }

            $dec = '0';
            for ($i = 0; $i < strlen($bin); $i++) {
                $dec = bcmul($dec, '2', 0);
                $dec = bcadd($dec, $bin[$i], 0);
            }
            $long = $dec;
        } elseif (self::isValidv4($ip)) {
            $long = ip2long($ip);
        }
        return $long;
    }
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;
	}
1220645
private function get_server_info() {
		$out = '<table>';

		// Validate if the server address is a valid IP-address.
		if ( $ipaddress = filter_input( INPUT_SERVER , 'SERVER_ADDR', FILTER_VALIDATE_IP ) ) {
			$out .= '<tr><td>IP</td><td>' . $ipaddress . '</td></tr>';
			$out .= '<tr><td>Hostname</td><td>' . gethostbyaddr( $ipaddress ) . '</td></tr>';
		}

		if ( function_exists( 'php_uname' ) ) {
			$out .= '<tr><td>OS</td><td>' . php_uname( 's r' ) . '</td></tr>';
		}

		$out .= '<tr><td>PHP</td><td>' . PHP_VERSION . '</td></tr>';
		$out .= '<tr><td>CURL</td><td>' . $this->get_curl_info() . '</td></tr>';
		$out .= '</table>';

		return $out;
	}
378634
public function getData( $ip = "" ){
		$this->ip = $ip;
		if( empty( $this->ip ) ) {
			throw new AddressNotFoundException(json_encode(['error' => 'No IP found for the user']));
		}
		// time to call api
		try{
			$request_params = $this->generateRequestParams();
			$res = self::client()->get( self::api_url() . 'data', $request_params);
		} catch ( RequestException $e) {
			if ($e->hasResponse()) {
				throw new GeotRequestException($e->getResponse());
			}
		}
		$this->validateResponse( $res );
		return $this->cleanResponse( $res );
	}
444771
function _decodeIP($ip)
    {
        $ip = base64_decode($ip);
        list(, $ip) = unpack('N', $ip);
        return long2ip($ip);
    }
780150
protected function getIpFromInfo($info)
    {
        $ip = \Piwik\Network\IP::fromStringIP($info['ip']);

        return $ip->toString();
    }
1000954
public function setVisitorIpAddress(&$ip)
    {
        $ipObject = IP::fromBinaryIP($ip);

        if (!$this->isActive()) {
            Common::printDebug("Visitor IP was _not_ anonymized: ". $ipObject->toString());
            return;
        }

        $privacyConfig = new Config();

        $newIpObject = self::applyIPMask($ipObject, $privacyConfig->ipAddressMaskLength);
        $ip = $newIpObject->toBinary();

        Common::printDebug("Visitor IP (was: ". $ipObject->toString() .") has been anonymized: ". $newIpObject->toString());
    }
914488
public static function expandIncompleteIpv6(string $ip): string
    {
        $hextets = array_map(function ($hextet) {
            return str_pad($hextet, 4, '0', STR_PAD_LEFT);
        }, explode(':', $ip));

        return implode(':', $hextets);
    }
189760
protected function _ip()
    {
        if (PSI_USE_VHOST === true) {
           if ((CommonFunctions::readenv('SERVER_ADDR', $result) || CommonFunctions::readenv('LOCAL_ADDR', $result)) //is server address defined
               && !strstr($result, '.') && strstr($result, ':')) { //is IPv6, quick version of preg_match('/\(([[0-9A-Fa-f\:]+)\)/', $result)
                $dnsrec = dns_get_record($this->sys->getHostname(), DNS_AAAA);
                if (isset($dnsrec[0]['ipv6'])) { //is DNS IPv6 record
                    $this->sys->setIp($dnsrec[0]['ipv6']); //from DNS (avoid IPv6 NAT translation)
                } else {
                    $this->sys->setIp(preg_replace('/^::ffff:/i', '', $result)); //from SERVER_ADDR or LOCAL_ADDR
                }
            } else {
                $this->sys->setIp(gethostbyname($this->sys->getHostname())); //IPv4 only
            }
        } else {
            if (CommonFunctions::readenv('SERVER_ADDR', $result) || CommonFunctions::readenv('LOCAL_ADDR', $result)) {
                $this->sys->setIp(preg_replace('/^::ffff:/i', '', $result));
            } else {
                $this->sys->setIp(gethostbyname($this->sys->getHostname()));
            }
        }
    }
607680
function ip() {
		$headers=$this->hive['HEADERS'];
		return isset($headers['Client-IP'])?
			$headers['Client-IP']:
			(isset($headers['X-Forwarded-For'])?
				explode(',',$headers['X-Forwarded-For'])[0]:
				(isset($_SERVER['REMOTE_ADDR'])?
					$_SERVER['REMOTE_ADDR']:''));
	}
345938
public static function makeGoodIP($ip)
    {

        $newIP = '';

        $ip_array = explode('.', $ip);

        if (is_array($ip_array)) {
            foreach ($ip_array as $val) {
                $newIP .= str_pad($val, 3, '0', STR_PAD_LEFT) . '.';
            }
        }
        $newIP = substr($newIP, 0, -1);

        return $newIP;
    }
474037
public static function expandIpv6(string $ip): string
    {
        if (!Validator::ipv6($ip)) {
            throw new \InvalidArgumentException(sprintf('"%s" is not a valid IPv6 address.', $ip));
        }

        $hex = unpack('H*hex', inet_pton($ip));

        return implode(':', str_split($hex['hex'], 4));
    }
783449
protected static function expandNotationIpv6($Ip)
    {
        if (strpos($Ip, '::') !== false)
        {
            $Ip = str_replace('::', str_repeat(':0', 8 - substr_count($Ip, ':')).':', $Ip);
        }
        if (strpos($Ip, ':') === 0)
        {
            $Ip = '0'.$Ip;
        }
        return $Ip;
    }
837244
protected function dlstatsIPv6ExpandNotation($Ip)
	{
		if (strpos($Ip, '::') !== false)
			$Ip = str_replace('::', str_repeat(':0', 8 - substr_count($Ip, ':')) . ':', $Ip);
		if (strpos($Ip, ':') === 0)
			$Ip = '0' . $Ip;
		return $Ip;
	}
850434
private function getlocationfromip($ip)
    {
        if (!$this->fp) {
            return null;
        } // 如果数据文件没有被正确打开，则直接返回空

        $location['ip'] = $ip;

        $ip = $this->packip($location['ip']); // 将输入的IP地址转化为可比较的IP地址
        // 不合法的IP地址会被转化为255.255.255.255
        // 对分搜索
        $l = 0; // 搜索的下边界
        $u = $this->totalip; // 搜索的上边界
        $findip = $this->lastip; // 如果没有找到就返回最后一条IP记录（qqwry.dat的版本信息）
        while ($l <= $u) { // 当上边界小于下边界时，查找失败
            $i = floor(($l + $u) / 2); // 计算近似中间记录
            fseek($this->fp, $this->firstip + $i * 7);
            $beginip = strrev(fread($this->fp, 4)); // 获取中间记录的开始IP地址
            // strrev函数在这里的作用是将little-endian的压缩IP地址转化为big-endian的格式
            // 以便用于比较，后面相同。
            if ($ip < $beginip) { // 用户的IP小于中间记录的开始IP地址时
                $u = $i - 1; // 将搜索的上边界修改为中间记录减一
            } else {
                fseek($this->fp, $this->getlong3());
                $endip = strrev(fread($this->fp, 4)); // 获取中间记录的结束IP地址
                if ($ip > $endip) { // 用户的IP大于中间记录的结束IP地址时
                    $l = $i + 1; // 将搜索的下边界修改为中间记录加一
                } else { // 用户的IP在中间记录的IP范围内时
                    $findip = $this->firstip + $i * 7;
                    break; // 则表示找到结果，退出循环
                }
            }
        }

        //获取查找到的IP地理位置信息
        fseek($this->fp, $findip);
        $location['beginip'] = long2ip($this->getlong()); // 用户IP所在范围的开始地址
        $offset = $this->getlong3();
        fseek($this->fp, $offset);
        $location['endip'] = long2ip($this->getlong()); // 用户IP所在范围的结束地址
        $byte = fread($this->fp, 1); // 标志字节
        switch (ord($byte)) {
            case 1: // 标志字节为1，表示国家和区域信息都被同时重定向
                $countryOffset = $this->getlong3(); // 重定向地址
                fseek($this->fp, $countryOffset);
                $byte = fread($this->fp, 1); // 标志字节
                switch (ord($byte)) {
                    case 2: // 标志字节为2，表示国家信息被重定向
                        fseek($this->fp, $this->getlong3());
                        $location['country'] = $this->getstring();
                        fseek($this->fp, $countryOffset + 4);
                        $location['area'] = $this->getarea();
                        break;
                    default: // 否则，表示国家信息没有被重定向
                        $location['country'] = $this->getstring($byte);
                        $location['area'] = $this->getarea();
                        break;
                }
                break;
            case 2: // 标志字节为2，表示国家信息被重定向
                fseek($this->fp, $this->getlong3());
                $location['country'] = $this->getstring();
                fseek($this->fp, $offset + 8);
                $location['area'] = $this->getarea();
                break;
            default: // 否则，表示国家信息没有被重定向
                $location['country'] = $this->getstring($byte);
                $location['area'] = $this->getarea();
                break;
        }

        $location['country'] = iconv("GBK", "UTF-8", $location['country']);
        $location['area'] = iconv("GBK", "UTF-8", $location['area']);

        if ($location['country'] == " CZ88.NET" || $location['country'] == "纯真网络") { // CZ88.NET表示没有有效信息
            $location['country'] = "无数据";
        }
        if ($location['area'] == " CZ88.NET") {
            $location['area'] = "";
        }

        return $location;
    }