(07-18-2024, 11:21 AM)Ahmed Sayed Wrote: Is there a function out of the box for Indy to use, or do I need to do this the hard way and loop through random numbers starting from specific numbers and keep going up until I find an open port?
You don't need to search manually at all. Simply bind the listening socket to port 0, and then the OS will pick an available ephemeral port for you. After the binding is finished, you can query the socket to know which port was chosen.
For example in Indy:
Code:
IdTCPServer.Bindings.Clear;
IdTCPServer.DefaultPort := 0;
// optional: populate IdTCPServer.Bindings for specific network adapters
// as needed, but set IdTCPServer.Bindings[Index].Port = 0...
IdTCPServer.Active := True;
for I := 0 to IdTCPServer.Bindings.Count-1 do begin
WriteLn('Listening on ' + IdTCPServer.Bindings[I].IP + ':' + IntToStr(IdTCPServer.Bindings[I].Port));
end;The same applies to UDP servers, too.
(07-18-2024, 11:21 AM)Ahmed Sayed Wrote: Currently, What I am doing is that I get the process ID and then adding 8000 to it and use that as the port number for the service, but I want a cleaner way to do so.
Obviously, that won't work for PID 57536 and higher. Also, just picking random ports is likely to run into conflicts at times. That is why the OS reserves a pool of ephemeral ports for apps to use.

