频道分类

Delphi 判断端口是否被使用

作者:admin 来源: 日期:2019/11/29 22:27:39 人气: 标签:

 
function TROMiddleWare.IsPortUsed(aPort: Integer): Boolean;
var
  _vSock: TSocket;
  _vWSAData: TWSAData;
  _vAddrIn: TSockAddrIn;
begin
  Result := False;
  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);
          if Bind(_vSock, _vAddrIn, SizeOf(_vAddrIn)) <> 0 then
            if WSAGetLastError = WSAEADDRINUSE then
              Result := True;
        end;
      finally
        CloseSocket(_vSock);
        WSACleanup();
      end;
    end;
  except
    Exit;
  end;
end;
————————————————

原文链接:https://blog.csdn.net/zjm12343/article/details/103278333