Getting the server port of a dedicated server

Hi, I have seen a lot of people having problems to get their dedicated server’s ports. I have a mothed to get the port upon the server creation.

    int32 port = 4032;
    bool foundport = false;
    for (size_t i = 0; foundport ==  false; i++)
    {
        port = 4032 + i;
        FIPv4Address ip = FIPv4Address(127, 0, 0, 1);
        FIPv4Address::Parse("127.0.0.1", ip);
        FIPv4Endpoint RemoteEndPointBind = FIPv4Endpoint(ip, port);
        FSocket* ListenServer = (FTcpSocketBuilder(TEXT("Test")));
        ISocketSubsystem* SocketSubsystem = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM);
        ListenServer->Bind(*SocketSubsystem->CreateInternetAddr(RemoteEndPointBind.Address.Value, RemoteEndPointBind.Port));
        ListenServer->Listen(8);
        ESocketErrors ErrorCode = SocketSubsystem->GetLastErrorCode();
        FString ErroCodeAsString = FString(SocketSubsystem->GetSocketError(ErrorCode));
        FStiring Error= "failed";
        if (ErrorCode) {
            UE_LOG(LogTemp, Display, TEXT("Logando '%s'"), *Error);
        }
        else {
            ListenServer->Close();
            foundport = true;
        }
        

    }
    
    
    FString ports = "- MainMap -server -log -port=" + FString::FromInt(port);
    FPlatformProcess::CreateProc(TEXT("G:\\Dominators Build\\WindowsServer\\EverstoneDominatorsServer.exe"), *ports, true, false, false, nullptr, 0, nullptr, nullptr);
}

With this you can test if a port is valid so you can bind it, and then you open the proccess with the port. Save this port in a variable for future communication with your dedicated server.

With this algorithm your players will never try to connect to empty ports.

Good luck, guys.

1 Like