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

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();
}

Leave a Comment