uses winsock2;
//获取一个空闲的端口
function GetFreePort(ABeginPort: Integer; const ATCP: Boolean = false): Integer;
var
Wsd: TWSAData;
S: Integer;
SockAddr: TSockAddrIn;
begin
Result := ABeginPort;
if WSAStartup(MAKEWORD(2, 2), Wsd) <> 0 then
Exit;
try
if ATCP then
S := Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
else
S := Socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if S = SOCKET_ERROR then
Exit;
SockAddr.sin_family := AF_INET;
SockAddr.sin_addr.S_addr := inet_addr(pchar(GetIP(false)));
SockAddr.sin_port := htons(ABeginPort);
while bind(S, @SockAddr, SizeOf(SockAddr)) = SOCKET_ERROR do
begin
inc(ABeginPort);
SockAddr.sin_port := htons(ABeginPort);
end;
closesocket(S);
finally
Result := ABeginPort;
end;
end;