Delphi中判断TCP端口是否被占用

uses WinSock

function PortOccupied(const APort:Integer):Boolean;
var
  S:TSocket;
  WSD :TWSAData;
  SockAddrIn:TSockAddrIn;
begin
  Result:=False;
  if (WSAStartup(MAKEWORD(2,2),WSD)= 0) then
  begin
    S := Socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    try
      if (S <> SOCKET_ERROR) then
      begin
        SockAddrIn.sin_family := AF_INET;
        SockAddrIn.sin_addr.S_addr := htonl(INADDR_ANY);
        //SockAddrIn.sin_addr.S_addr := inet_addr(PAnsiChar(AnsiString(IP)));
        SockAddrIn.sin_port:= htons(APort);
        if (Bind(S,SockAddrIn,SizeOf(SockAddrIn))<>0) then
          if (WSAGetLastError = WSAEADDRINUSE) then
            Result:=True;
      end;
    finally
      CloseSocket(S);
      WSACleanup();
    end;
  end;
end;


发表评论

电子邮件地址不会被公开。 必填项已用*标注

67 − = 62