How to get the SPRING Boot HOST and PORT address during run time?

Anezka L. picture Anezka L. · Aug 12, 2016 · Viewed 51.4k times · Source

How could I get the host and port where my application is deployed during run-time so that I can use it in my java method?

Answer

Anton Novopashin picture Anton Novopashin · Aug 12, 2016

You can get this information via Environment for the port and the host you can obtain by using InternetAddress.

@Autowired
Environment environment;

// Port via annotation
@Value('${server.port}')
int aPort;

......
public void somePlaceInTheCode() {
    // Port
    environment.getProperty("server.port");
    
    // Local address
    InetAddress.getLocalHost().getHostAddress();
    InetAddress.getLocalHost().getHostName();
    
    // Remote address
    InetAddress.getLoopbackAddress().getHostAddress();
    InetAddress.getLoopbackAddress().getHostName();
}