Spring Boot
local server
host and port
Spring Boot configuration
Java development

How to get local server host and port in Spring Boot?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Getting the local server port in Spring Boot is straightforward once the embedded web server has started. Getting the host is more nuanced, because the server may bind to all interfaces, in which case there is no single meaningful host name unless you choose one for your own local URL generation.

Understand configured values versus runtime values

Spring Boot exposes configuration such as server.port, but that is not always the same as the actual runtime port. If you use server.port=0, the framework asks the operating system for a free port, so you must read the value after startup from the running web server.

For the host, server.address may be unset. When that happens, the application is typically bound to all available interfaces rather than one specific local host string.

Read the runtime port from the web server

A reliable pattern is to listen for WebServerInitializedEvent and store the assigned port.

java
1import java.net.InetAddress;
2import org.springframework.beans.factory.annotation.Value;
3import org.springframework.boot.web.context.WebServerInitializedEvent;
4import org.springframework.context.event.EventListener;
5import org.springframework.stereotype.Component;
6
7@Component
8public class LocalServerInfo {
9    private int port;
10
11    @Value("${server.address:}")
12    private String configuredAddress;
13
14    @EventListener
15    public void onWebServerReady(WebServerInitializedEvent event) {
16        this.port = event.getWebServer().getPort();
17    }
18
19    public int getPort() {
20        return port;
21    }
22
23    public String getHost() {
24        if (configuredAddress != null && !configuredAddress.isBlank()) {
25            return configuredAddress;
26        }
27        return InetAddress.getLoopbackAddress().getHostAddress();
28    }
29
30    public String getBaseUrl() {
31        return "http://" + getHost() + ":" + getPort();
32    }
33}

This is a good general solution for application code that needs to log or publish its own local base URL.

Use @LocalServerPort in tests

If the real use case is integration testing, Spring Boot already provides a simpler option.

java
1import org.junit.jupiter.api.Test;
2import org.springframework.boot.test.context.SpringBootTest;
3import org.springframework.boot.test.web.server.LocalServerPort;
4
5@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
6class DemoApplicationTests {
7
8    @LocalServerPort
9    int port;
10
11    @Test
12    void printsPort() {
13        System.out.println(port);
14    }
15}

This is the right choice in tests because it avoids manual event handling and integrates cleanly with random-port startup.

Host is a design decision, not always a discoverable fact

Many questions about host and port really mean, "How do I build a URL for my app?" Port is usually discoverable. Host often is not, because a server bound to 0.0.0.0 can be reached through several addresses. In that situation you normally choose a local loopback host such as 127.0.0.1 for local URLs or use a configured public host name when running behind a proxy.

That distinction matters. If you present one host value as if it were the only true answer, you can create misleading links in containerized or cloud setups.

Servlet versus reactive applications

The overall idea is the same for servlet and reactive stacks: wait until the web server exists, then read the assigned port from the running server context. What changes is the surrounding application type, not the need to distinguish configured properties from the actual runtime listener.

Common Pitfalls

  • Reading server.port too early and expecting it to reflect the assigned random port.
  • Treating server.address as mandatory when it is often unset.
  • Assuming there is always one correct host string even when the server listens on all interfaces.
  • Using @LocalServerPort in normal application code instead of tests.
  • Building absolute URLs without considering proxies, forwarded headers, or deployment-specific host names.

Summary

  • Read the runtime port after startup if the server chooses it dynamically.
  • 'WebServerInitializedEvent is a reliable application-level hook for that.'
  • Use @LocalServerPort when the need is test-specific.
  • Host discovery is contextual because a server can bind to multiple interfaces.
  • For local URLs, choose an explicit host strategy instead of assuming Spring Boot always has one canonical answer.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.