Skip to content

Conversation

@ranjitm2001
Copy link

Description

This PR adds support for retrieving mapped ports with protocol specification, enabling proper UDP port mapping support as requested in #554.

Changes

New Methods

  1. ContainerState.getMappedPort(int originalPort, InternetProtocol protocol)

    • A new overload of getMappedPort that accepts an InternetProtocol parameter (TCP or UDP)
    • The existing getMappedPort(int) method now delegates to this with TCP as the default protocol
    • Returns the mapped host port for the given container port and protocol
  2. Container.addExposedPort(int port, InternetProtocol protocol)

    • New interface method for adding ports with specific protocols
    • Implemented in GenericContainer

Benefits

Before this change, getting a UDP mapped port required verbose code:

container.getContainerInfo().getNetworkSettings().getPorts().getBindings()
    .get(new ExposedPort(originalPort, protocol))[0].getHostPortSpec()

Now users can simply use:

container.getMappedPort(5353, InternetProtocol.UDP)

Use Cases

  • Testing Jaeger (UDP ports 5775, 6831, 6832)
  • Testing DNS services (UDP port 53)
  • Testing network flow services (Netflow, sFlow, IPFix)
  • Any service that exposes UDP ports

Testing

Added 4 new unit tests in ContainerStateTest:

  • shouldGetMappedPortForUdpProtocol() - Tests UDP port mapping retrieval
  • shouldGetMappedPortForTcpUsingProtocol() - Tests TCP port mapping with explicit protocol
  • shouldThrowForUnmappedUdpPort() - Tests error handling for unmapped ports
  • shouldSupportBothTcpAndUdpOnSamePort() - Tests using same port number for both TCP and UDP

All 10 tests in ContainerStateTest pass.

Closes #554

This commit adds support for retrieving mapped ports with protocol
specification, enabling proper UDP port mapping support.

Changes:
- ContainerState: Add getMappedPort(int, InternetProtocol) method that
  supports both TCP and UDP protocols. The existing getMappedPort(int)
  now delegates to this method with TCP as the default protocol.
- Container: Add addExposedPort(int, InternetProtocol) to the interface
  for adding ports with specific protocols.
- GenericContainer: Implement addExposedPort(int, InternetProtocol).
- ContainerStateTest: Add unit tests for UDP port mapping functionality.

Fixes testcontainers#554
@ranjitm2001 ranjitm2001 requested a review from a team as a code owner December 29, 2025 03:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add getMappedPort(Integer originalPort, InternetProtocol protocol)

1 participant