Change record status: 
Project: 
Introduced in branch: 
8.x
Description: 

In Drupal 8 ip_address() has been removed in favor of Request::getClientIp()

The recommended way to access a client's IP address in Drupal 8 is to register an object with the service container and depend on the request service.This way the correct request object will be always provided. If that's not possible Drupal::request() can be used to access the current registered Request object.

D7

Procedural Code

if ($ip == ip_address()) {
  drupal_set_message('ip', t('You may not ban your own IP address.'));
}

OOP

class Foo {
  public function bar() {
    if ($ip == ip_address()) {
      drupal_set_message('ip', t('You may not ban your own IP address.'));
    }
  }
}

D8

Procedural Code

if ($ip == Drupal::request()->getClientIp()) {
  drupal_set_message('ip', t('You may not ban your own IP address.'));
}

OOP

In your MYMODULE/MYMODULE.service.yml :

services:
  foo:
    class: Drupal\MYMODULE\Foo
    arguments: ['@request_stack']

In MYMODULE/src/Foo.php


namespace Drupal\MYMODULE;

use Symfony\Component\HttpFoundation\RequestStack;

class Foo {

  /**
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;
  
  /**
   * Constructs a Foo object.
   *
   * @param Symfony\Component\HttpFoundation\RequestStack $request
   *   The request object.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  public function bar() {
    $ip = $this->requestStack->getCurrentRequest()->getClientIp();
    // Do something with $ip.
  }

}
Impacts: 
Module developers
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done