Porting PHP code to Delphi code [closed]

↘锁芯ラ 提交于 2019-12-07 04:26:25

Warning: I haven't written this in an IDE, but any syntax errors should be easy to fix. The logic around "send a command, read a line, see if it's a 250 response code" should really be pulled out into a separate function. I haven't done so so the code resembles the original PHP a bit more closely. (I have a CheckOK because I couldn't stop myself.)

function CheckOK(Response: String): Boolean;
var
  Code: Integer;
  SpacePos: Integer;
  Token: String;
begin
  SpacePos := Pos(' ', Response);
  Token := Copy(Response, 1, SpacePos);
  Code := StrToIntDef(Token, -1);
  Result := Code = 250;
end;

function TorNewIdentity(TorIP: String = '127.0.0.1'; ControlPort: Integer = 9051; AuthCode: String = ''): Boolean
var
  C: TIdTcpClient;
  Response: String;
begin 
  Result := true;

  C := TIdTcpClient.Create(nil);
  try
    C.Host := TorIP;
    C.Port := ControlPort;
    C.Connect(5000); // milliseconds

    C.WriteLn('AUTHENTICATE ' + AuthCode);
    // I assume here that the response will be a single CRLF-terminated line.
    Response := C.ReadLn;
    if not CheckOK(Response) then begin
      // Authentication failed.
      Result := false;
      Exit;
    end;

    C.WriteLn('signal NEWNYM');
    Response := C.ReadLn;
    if not CheckOK(Response) then begin
      // Signal failed.
      Result := false;
      Exit;
    end;
  finally
    C.Free;
  end; 
end;

A small error in previous answer. In function CheckOK Result := Code <> 250; should to be changed to Result := (Code = 250);

PS: Sorry, I see no way to post a comment to the original answer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!