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

74,761

Solution 1

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

Solution 2

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

Solution 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;
}

Solution 4

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

Solution 5

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

Share:
74,761
Admin
Author by

Admin

Updated on April 30, 2021

Comments

  • Admin
    Admin over 2 years

    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?

  • Nicolai Ehemann
    Nicolai Ehemann almost 7 years
    Getting 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<EmbeddedServletContainerInitializedEvent‌​> and get the port from the provided event.
  • azizunsal
    azizunsal about 6 years
    Using local.server.port instead of server.port would be a better choice in the case of random port is used(server.port=0).
  • user2652379
    user2652379 about 5 years
    The loopback address(127.0.0.1) is a remote address?
  • Heybat
    Heybat almost 3 years
    what is the difference between "Local address" and "Remote address" address?