package org.testcontainers.containers.wait.internal;

import lombok.RequiredArgsConstructor;
import org.testcontainers.containers.ContainerState;

import java.io.IOException;
import java.net.Socket;
import java.util.Set;
import java.util.concurrent.Callable;

/**
 * Mechanism for testing that a socket is listening when run from the test host.
 */
@RequiredArgsConstructor
public class ExternalPortListeningCheck implements Callable<Boolean> {
    private final ContainerState containerState;
    private final Set<Integer> externalLivenessCheckPorts;

    @Override
    public Boolean call() {
        String address = containerState.getHost();

        externalLivenessCheckPorts.parallelStream().forEach(externalPort -> {
            try {
                new Socket(address, externalPort).close();
            } catch (IOException e) {
                throw new IllegalStateException("Socket not listening yet: " + externalPort);
            }
        });
        return true;
    }
}

@@ -168,16 +168,51 @@
 eption;%0A
+import java.net.InetSocketAddress;%0A
 import j
@@ -774,66 +774,195 @@
 try 
-%7B%0A                new Socket(address, externalPort).close(
+(Socket socket = new Socket()) %7B%0A                InetSocketAddress inetSocketAddress = new InetSocketAddress(address, externalPort);%0A                socket.connect(inetSocketAddress, 1000
 );%0A 

Change external port check so it can timeout and retry (#4680)