En esta entrada vamos a aprender cómo obtener la dirección IP del navegador del cliente cuando este visite nuestra aplicación web con Spring Boot.

1. Crear proyecto web Spring Boot

Desde el IDE de Intellij Idea, seleccione New Project > Spring Initializr > Completar los campos solicitados.

Welcome to IntelliJ IDEA
New Porject

En la ventana emergente New Project seleccionamos Spring Initializr y en el Project Dependencies, elija las siguientes dependencias.

  • Thymeleaf.
  • Spring Web.
  • Lombok.
  • Spring Native.
  • Spring Boot DevTools.

2. Crear interfaz de servicio de solicitud

Cree un nuevo paquete fuente de Java llamado co.danydev.obtenerip.services, luego agregue una nueva interfaz RequestService con la siguiente definición.

package co.danydev.obtenerip.services;

import javax.servlet.http.HttpServletRequest;

public interface RequestService {
    
    String getClientIp(HttpServletRequest request);
    
}

3. Implementamos el servicio de solicitud para obtener la dirección IP del cliente.

Cree un nuevo paquete Java llamado co.danydev.obtenerip.services.impl y creamos la clase RequestServiceImpl

package co.danydev.obtenerip.services.impl;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import co.danydev.obtenerip.services.RequestService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class RequestServiceImpl implements RequestService {

    private final String LOCALHOST_IPV4 = "127.0.0.1";
    private final String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1";

    @Override
    public String getClientIp(HttpServletRequest request) {

        String ipAddress = request.getHeader("X-Forwarded-For");

        if (StringUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }

        if (StringUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }

        if (StringUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (LOCALHOST_IPV4.equals(ipAddress) || LOCALHOST_IPV6.equals(ipAddress)) {
                try {
                    InetAddress inetAddress = InetAddress.getLocalHost();
                    ipAddress = inetAddress.getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }

        if (!StringUtils.isEmpty(ipAddress)
                && ipAddress.length() > 15
                && ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }

        return ipAddress;
    }
}

Creación del controlador y ver para mostrar la dirección IP del cliente

Cree un nuevo paquete Java llamado co.danydev.obtenerip.controller y agregue la clase de controlador HomeController.

package co.danydev.obtenerip.controllers;

import co.danydev.obtenerip.services.RequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
public class HomeController {

    @Autowired
    private RequestService requestService;

    @RequestMapping("/")
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView model = new ModelAndView("index");
        String clientIp = requestService.getClientIp(request);
        model.addObject("clientIp", clientIp);
        return model;
    }

}

Agregue el archivo index.html en \src\main\resources\templates\index.html e implemente la vista Thymeleaf como el siguiente código.

<!DOCTYPE html>
<html>
	<head>
		<title>Client IP</title>
	</head>
	<body>
		<h1>Your IP Address: <span th:text="${clientIp}"></span></h1>
	</body>
</html>

Ejecute la aplicación Spring Boot y visite la aplicación web en su navegador local en localhost:8080