此程式會檢查給的port 是否已經被使用,如果是就+1,直到找到空著(沒有被使用)的埠為止。
function TNetServer.GetFreePort(aPort: Integer): Integer; var _vSock: TSocket; _vWSAData: TWSAData; _vAddrIn: TSockAddrIn; begin try if WSAStartup(MAKEWORD(2, 2), _vWSAData) = 0 then begin _vSock := Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); try if _vSock <> SOCKET_ERROR then begin _vAddrIn.sin_family := AF_INET; _vAddrIn.sin_addr.S_addr := htonl(INADDR_ANY); _vAddrIn.sin_port := htons(APort); while (Bind(_vSock, _vAddrIn, SizeOf(_vAddrIn)) <> 0) and (WSAGetLastError = WSAEADDRINUSE) do begin inc(aPort); _vAddrIn.sin_port := htons(aPort); end; end; finally CloseSocket(_vSock); WSACleanup(); end; end; finally Result := aPort; end; end;
如果有需要指定範圍,可在 18, 19行間增加如下:
if aPort > XXXXX then aPort := OOOOO;
XXXXX 是最大的埠號值
OOOOO 是最小的埠號值
OOOOO 是最小的埠號值