protected function getClientIPAddress(array $server): ?string
    {
        $serverRemoteAddress = $server['REMOTE_ADDR'] ?? null;

        if ($this->isUsingTrustedProxy($server)) {
            return $serverRemoteAddress ?? null;
        }

        $ipAddresses = [];

        // RFC 7239
        if (isset($server[$this->trustedHeaderNames['HTTP_FORWARDED']])) {
            $header = $server[$this->trustedHeaderNames['HTTP_FORWARDED']];
            preg_match_all("/for=(?:\"?\[?)([a-z0-9:\.\-\/_]*)/", $header, $matches);
            $ipAddresses = $matches[1];
        } elseif (isset($server[$this->trustedHeaderNames['HTTP_CLIENT_IP']])) {
            $ipAddresses = explode(',', $server[$this->trustedHeaderNames['HTTP_CLIENT_IP']]);
            $ipAddresses = array_map('trim', $ipAddresses);
        }

        if ($serverRemoteAddress !== null) {
            $ipAddresses[] = $serverRemoteAddress;
        }

        $fallbackIPAddresses = count($ipAddresses) === 0 ? [] : [$ipAddresses[0]];

        foreach ($ipAddresses as $index => $ipAddress) {
            // Check for valid IP address
            if (filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
                unset($ipAddresses[$index]);
            }

            // Don't accept trusted proxies
            if (in_array($ipAddress, $this->trustedProxyIPAddresses, true)) {
                unset($ipAddresses[$index]);
            }
        }

        $clientIPAddresses = count($ipAddresses) === 0 ? $fallbackIPAddresses : array_reverse($ipAddresses);

        return $clientIPAddresses[0] ?? null;
    }