我有两个进程必须在 PC 上的两个空闲 TCP 端口上运行。对于它的用户来说,这必须是一个无痛的开箱即用过程,我想自动检测空闲端口以避免冲突并将这些端口号应用于这两个进程。
为了实现这一点,我制作了一个函数(也在线程中运行)来检测空闲端口,但没有找到任何空闲端口。有人可以解释我的代码有什么问题吗?
编辑:“@500-error etc”提供的解决方案应用于代码。现在功能正常。
这里是:
uses
winsock;
type
TAvailablePortArray = array of Word;
function findAvailableTCPPort( ipAddressStr : String; portStart : Word = 8080; portEnd : Word = 8084; findCount : Byte = 2 ) : TAvailablePortArray;
var
client : sockaddr_in;
sock : Integer;
ret : Integer;
wsdata : WSAData;
dwPort : Word;
iFound : Byte;
bResult : Boolean;
bAllFound : Boolean;
dns : PHostEnt;
status : LongInt;
begin
setLength( Result, 0 );
if( portStart > portEnd ) or ( portStart = 0 ) or ( findCount = 0 ) then
Exit;
try
ret := WSAStartup($0002, wsdata); //initiates use of the Winsock DLL
except
ret:=-1;
end;
if( ret <> 0 ) then
Exit;
dns:=getHostByName( PChar(ipAddressStr) );
if( NOT Assigned( dns )) then
Exit;
bResult:=TRUE;
try
fillChar( client, sizeOf( client ), 0 );
client.sin_family := AF_INET; //Set the protocol to use , in this case (IPv4)
client.sin_addr.s_addr :=LongInt(PLongInt(dns^.h_addr_list^)^);
//inet_addr(PAnsiChar(ipAddressStr)); //convert to IN_ADDR structure
except
bResult:=FALSE;
end;
if( bResult ) then
begin
dwPort:=portStart;
setLength( Result, findCount );
bAllFound:=FALSE;
iFound:=0;
while( NOT bAllFound ) and ( dwPort <= portEnd ) do
begin
try
client.sin_port:=htons(dwPort); //convert to TCP/IP network byte order (big-endian)
sock:=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP ); //creates a socket
Application.processMessages();
status:=connect(sock,client,sizeOf(client));
bResult:=(status <> 0); //establishes a connection to a specified socket, less than zero is NOT in use
except
bResult:=FALSE;
end;
if( sock <> 0 ) then
begin
closesocket(sock);
sock:=0;
end;
if( bResult ) then
begin
Result[iFound]:=dwPort;
inc( iFound );
bAllFound:=( iFound = findCount );
end;
inc(dwPort);
end;
end;
if( NOT bAllFound ) then
setLength( Result, 0 );
try
WSACleanup();
except;
end;
end;
调用上述函数的一些代码:
procedure TForm1.btStartClick(Sender: TObject);
begin
addLogMsg( 'Starting service ...' );
FPorts:=findAvailableTCPPort( '127.0.0.1' );
FPortCount:=Length( FPorts );
addLogMsg( 'Available ports found: '+strToInt( FPortCount ));
if( FPortCount < 2 ) then
begin
addLogMsg( 'ERROR: Cannot start service(s), insufficient free ports!' );
Exit;
end;
................
................
................
end;
我做错了什么?
注意:我已经调试了代码,过程似乎没问题(它试图测试它,没有例外)。还通过使用其他应用程序对其进行测试来验证指定的端口未在使用中。