Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-boot REST API print caller Address

Tags:

spring-boot

I am trying to print the IP address of the requester of my web service. I am a beginner with spring-boot, and I am not sure which class to import or variable to use to print the caller IP and port number. This is my controller class :

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;//added
import org.springframework.web.bind.annotation.RequestParam;//added
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.sql.*;

//Controller
@RestController
public class MyController {

    @GetMapping(path = "/print-caller-address")
    public String CallerAddress() {
        return "Caller IP or Port Number";
    }
}

I am using spring-boot-starter-web and spring-boot-starter-data-jpa as dependencies.

Many thanks.

like image 900
ANehme Avatar asked Dec 02 '25 10:12

ANehme


1 Answers

Try this:

@RestController
public class MyController {

    @GetMapping(path = "/print-caller-address")
    public String getCallerAddress(HttpServletRequest request) {
        return request.getRemoteAddr();
    }
}

https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getRemoteAddr()

Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.

If the request has gone through a proxy before hitting your REST server then you would need to look at the headers. The proxy will typically set a header idientifyign the originating IP, address as detailed below:

https://en.wikipedia.org/wiki/X-Forwarded-For

so you can use request.getHeader("X-Forwarded-For") to get the originating IP address. To catch all scenarios:

@RestController
public class MyController {

    @GetMapping(path = "/print-caller-address")
    public String getCallerAddress(HttpServletRequest request) {
        if(request.getHeader("X-Forwarded-For") != null){
            return request.getHeader("X-Forwarded-For")
        }else{
            return request.getRemoteAddr();
        }
    }
}
like image 52
Alan Hay Avatar answered Dec 06 '25 16:12

Alan Hay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!