Skip to content

Commit

Permalink
Return local IP when proxy IP detection fails
Browse files Browse the repository at this point in the history
Fixes #3
  • Loading branch information
shadowhand committed Jul 13, 2017
1 parent 728e89e commit 09fac8c
Showing 1 changed file with 46 additions and 13 deletions.
59 changes: 46 additions & 13 deletions src/ClientIp.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,32 +107,65 @@ public function process(ServerRequestInterface $request, DelegateInterface $dele
*/
private function getIp(ServerRequestInterface $request)
{
if ($this->remote) {
$ip = file_get_contents('http://ipecho.net/plain');
if ($ip = $this->getRemoteIp()) {
return $ip;
}

if (self::isValid($ip)) {
if ($ip = $this->getProxyIp($request)) {
if (!in_array($ip, $this->proxyIps)) {
return $ip;
}
}

$ip = null;
$server = $request->getServerParams();

if (!empty($server['REMOTE_ADDR']) && self::isValid($server['REMOTE_ADDR'])) {
$ip = $server['REMOTE_ADDR'];
}
return $this->getLocalIp($request);
}

if (empty($this->proxyHeaders) || (!empty($this->proxyIps) && !in_array($ip, $this->proxyIps))) {
return $ip;
/**
* Returns the IP address from remote service.
*
* @return string|null
*/
private function getRemoteIp()
{
if ($this->remote) {
$ip = file_get_contents('http://ipecho.net/plain');
if (self::isValid($ip)) {
return $ip;
}
}
}

/**
* Returns the first valid proxied IP found.
*
* @return string|null
*/
private function getProxyIp(ServerRequestInterface $request)
{
foreach ($this->proxyHeaders as $name) {
if ($request->hasHeader($name) && ($ip = self::getHeaderIp($request->getHeaderLine($name))) !== null) {
return $ip;
if ($request->hasHeader($name)) {
$ip = self::getHeaderIp($request->getHeaderLine($name));
if (self::isValid($ip)) {
return $ip;
}
}
}
}

/**
* Returns the remote address of the request, if valid.
*
* @return string|null
*/
private function getLocalIp(ServerRequestInterface $request)
{
$server = $request->getServerParams();

if (!empty($server['REMOTE_ADDR']) && self::isValid($server['REMOTE_ADDR'])) {
return $server['REMOTE_ADDR'];
}
}

/**
* Returns the first valid ip found in the header.
*
Expand Down

0 comments on commit 09fac8c

Please sign in to comment.