HanDs
管理员

[Delphi文章] 判断TCP端口是否被占用 



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;


学习中请遵守法律法规,本网站内容均来自于互联网,本网站不负担法律责任
判断
#1楼
发帖时间:2016-7-9   |   查看数:0   |   回复数:0
游客组
快速回复