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?
-
How do you define the port of spring boot application ? – Mickael Aug 12 '16 at 13:11
-
Does this answer your question? [How to get local server host and port in Spring Boot?](https://stackoverflow.com/questions/29929896/how-to-get-local-server-host-and-port-in-spring-boot) – Ilya Serbis Mar 12 '20 at 22:57
-
This solved my issue, alltogether: https://stackoverflow.com/questions/75722327/how-to-get-host-url-in-spring-boot-controller – rpajaziti Jun 07 '23 at 13:21
6 Answers
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();
}
-
8Getting the port this way will only work, if a) the port is actually configured explicitly, and b) it is not set to 0 (meaning the servlet container will choose a random port on startup). To get the actual port, you need to implement `ApplicationListener
` and get the port from the provided event. – Nicolai Ehemann Jan 06 '17 at 08:20 -
4Using `local.server.port` instead of `server.port` would be a better choice in the case of random port is used(`server.port=0`). – azizunsal Aug 22 '17 at 08:09
-
1
-
what is the difference between "Local address" and "Remote address" address? – Heybat Dec 18 '20 at 10:16
If you use random port like server.port=${random.int[10000,20000]}
method. and in Java code read the port in Environment
use @Value
or getProperty("server.port")
. You will get a Unpredictable Port Because it is Random.
ApplicationListener, you can override onApplicationEvent to get the port number once it's set.
In Spring boot version Implements Spring interface ApplicationListener<EmbeddedServletContainerInitializedEvent>
(Spring boot version 1) or ApplicationListener<WebServerInitializedEvent>
(Spring boot version 2) override onApplicationEvent to get the Fact Port .
Spring boot 1
@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
int port = event.getEmbeddedServletContainer().getPort();
}
Spring boot 2
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
Integer port = event.getWebServer().getPort();
this.port = port;
}

- 111
- 1
- 3
Here is an util component:
EnvUtil.java
(Put it in proper package, to become a component.)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Environment util.
*/
@Component
public class EnvUtil {
@Autowired
Environment environment;
private String port;
private String hostname;
/**
* Get port.
*
* @return
*/
public String getPort() {
if (port == null) port = environment.getProperty("local.server.port");
return port;
}
/**
* Get port, as Integer.
*
* @return
*/
public Integer getPortAsInt() {
return Integer.valueOf(getPort());
}
/**
* Get hostname.
*
* @return
*/
public String getHostname() throws UnknownHostException {
// TODO ... would this cache cause issue, when network env change ???
if (hostname == null) hostname = InetAddress.getLocalHost().getHostAddress();
return hostname;
}
public String getServerUrlPrefi() throws UnknownHostException {
return "http://" + getHostname() + ":" + getPort();
}
}
Example - use the util:
Then could inject the util, and call its method.
Here is an example in a controller:
// inject it,
@Autowired
private EnvUtil envUtil;
/**
* env
*
* @return
*/
@GetMapping(path = "/env")
@ResponseBody
public Object env() throws UnknownHostException {
Map<String, Object> map = new HashMap<>();
map.put("port", envUtil.getPort());
map.put("host", envUtil.getHostname());
return map;
}

- 22,183
- 20
- 145
- 196
For the Host: As mentionned by Anton
// Local address
InetAddress.getLocalHost().getHostAddress();
InetAddress.getLocalHost().getHostName();
// Remote address
InetAddress.getLoopbackAddress().getHostAddress();
InetAddress.getLoopbackAddress().getHostName();
Port: As mentioned by Nicolai, you can retrieve this information by the environment property only if it is configured explicitly and not set to 0.
Spring documentation on the subject: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html#howto-discover-the-http-port-at-runtime
For the actual way to do this, it was answered here: Spring Boot - How to get the running port
And here's a github example on how to implement it: https://github.com/hosuaby/example-restful-project/blob/master/src/main/java/io/hosuaby/restful/PortHolder.java

- 41
- 3
Just a complete example for answers above
package bj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import java.net.InetAddress;
import java.net.UnknownHostException;
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@SpringBootApplication
class App implements ApplicationListener<ApplicationReadyEvent> {
@Autowired
private ApplicationContext applicationContext;
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
try {
String ip = InetAddress.getLocalHost().getHostAddress();
int port = applicationContext.getBean(Environment.class).getProperty("server.port", Integer.class, 8080);
System.out.printf("%s:%d", ip, port);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}

- 3,716
- 1
- 30
- 28
The port has been bind in runtime could been injected as:
@Value('${local.server.port}')
private int port;

- 37
- 11