Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
Bind and Listen on an Available Port in a Range
See more Socket/SSL/TLS Examples
Demonstrates Socket.BindAndListenPortRange, which searches an inclusive port range for an available TCP port, binds it, and begins listening. It returns the selected port, or -1 on failure.
Background. This is useful when any of several ports is acceptable and the application needs to discover which one was bound.
Chilkat Pascal (Lazarus/Delphi) Downloads
program ChilkatDemo;
// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils,
CkDllLoader,
Chilkat.Socket;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
socket: TSocket;
boundPort: Integer;
begin
socket := TSocket.Create;
// Search the inclusive port range for an available TCP port, bind it, and begin listening. The
// method returns the selected port, or -1 when no port can be bound.
boundPort := socket.BindAndListenPortRange(5000,5100,25);
if (boundPort < 0) then
begin
WriteLn(socket.LastErrorText);
Exit;
end;
WriteLn('Listening on port ' + boundPort);
socket.Free;
end;
// ---------------------------------------------------------------------------
begin
try
RunDemo;
except
on E: Exception do
WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
end;
WriteLn;
{$IFDEF MSWINDOWS}
WriteLn('Press Enter to exit...');
ReadLn;
{$ENDIF}
end.