将PHP代码移植到Delphi代码

时间:2010-10-22 18:06:23

标签: php delphi indy

我正在努力将tor集成到我的Delphi应用程序中;整个故事is explained in this link

之后我搜索了互联网,然后我发现了一个用PHP切换新身份的代码

 function tor_new_identity($tor_ip='127.0.0.1', $control_port='9051', $auth_code=''){
    $fp = fsockopen($tor_ip, $control_port, $errno, $errstr, 30);
    if (!$fp) return false; //can't connect to the control port

    fputs($fp, "AUTHENTICATE $auth_code\r\n");
    $response = fread($fp, 1024);
    list($code, $text) = explode(' ', $response, 2);
    if ($code != '250') return false; //authentication failed

    //send the request to for new identity
    fputs($fp, "signal NEWNYM\r\n");
    $response = fread($fp, 1024);
    list($code, $text) = explode(' ', $response, 2);
    if ($code != '250') return false; //signal failed

    fclose($fp);
    return true;
}

任何人都可以帮我把它移植到Delphi / Pascal

我不知道任何PHP基础知识

提前致谢

问候

2 个答案:

答案 0 :(得分:4)

警告:我没有在IDE中编写此代码,但任何语法错误都应该很容易修复。关于“发送命令,读取一条线,看看它是否为250响应代码”的逻辑应该真正被拉出到一个单独的函数中。我还没有这样做,所以代码更接近原始PHP。 (我有一个CheckOK,因为我无法阻止自己。)

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;

答案 1 :(得分:1)

上一个答案中的一个小错误。在功能CheckOK中 结果:=代码<> 250; 应该改为 结果:=(代码= 250);

PS:抱歉,我认为无法对原始答案发表评论。