program tserver;
{$M 16536,8192}

uses dvcrt, dvwin, dvinet, winsock, strings;

var
    arq_respost, arq_form1, arq_form2: text;
    sockListen, sock: integer;
    s: string;
    meuBuf: pbufRede;
    numero: string;

procedure infIp;
var
    localAddr: sockaddr_in;
    tam: integer;

begin
    fillchar (localAddr, sizeof (localAddr), 0);
    tam := sizeof (localAddr);
    getSockName (sock, localAddr, tam);
    sintwrite ('Número IP desta conexão : ');
    numero:= (strpas (inet_ntoa (localAddr.sin_addr.s_addr)));
    sintwriteln (numero);

end;

procedure reeditaForm;
var s1, s2: string;
begin

    assign (arq_form1, 'tform.htm');
    reset (arq_form1);

    assign (arq_form2, 'tform.$$$');
    rewrite (arq_form2);

    while not eof (arq_form1) do
    begin
        readln (arq_form1, s1);
        s2:= copy (s1, 1, 5);
        if s2 = '<FORM' then
        begin
            write (arq_form2, '<FORM METHOD="GET" ACTION="http://');
            write (arq_form2, (numero));
            writeln (arq_form2, '">');
        end
        else
            writeln (arq_form2, s1);
end;

    erase (arq_form1);
    close (arq_form2);
    rename (arq_form2, 'tform.htm');
    close (arq_form1);

end;

begin
    sintInic (2, '');

    assign (arq_respost, 'resposta.web');
    {$i-} append (arq_respost); {$i+}
    If IOresult <> 0  then
    rewrite (arq_respost);

    abreWinSock;

    {infIp;
    write (arq_respost, 'Número IP deste servidor : ');
    writeln (arq_respost, numero);}

    {reeditaForm;}

    sintWriteln ('esperando');
    sockListen := escutaConexao (80);
    repeat
         delay (500);
    until chegouRede (sockListen);

    sock := aceitaConexao (sockListen);
    sintbip; sintbip; sintbip;
    sintWriteln ('conectou');
    fechaConexao (sockListen);

    meuBuf := inicBufRede (sock);
    s := '';
    repeat
        if chegouRede (sock) then
             begin
                 if readlnBufRede (meuBuf, s) then
                 begin
                     sintwriteln (s);
                     writeln (arq_respost, s);
                 end
                 else
                     s := 'fim';
             end;
    until s = 'fim';

    close (arq_respost);

    fimBufRede (meuBuf);
    fechaConexao (sock);
    fechaWinSock;

    donewincrt;
    sintFim;
end.
