program Loopback;

uses
  Crt,
  CoBase,
  CoIPV4,
  CoEthDef,
  CoEth01,
  CoINET,
  CoUDP,
  NumToStr;



procedure LoopbackTest;
var
  Sock     : PCoDevice;
  Status   : TCoStatus;
  Buffer   : array[0..199] of Byte;
  RecvLen  : Word;
  SrcAddr  : TUdpAddress;
  DstAddr  : TUdpAddress;
begin

  Status := NetOpenSocket( 'UDP', 'LPORT=5000', '', Sock );

  if Status <> CST_SUCCESS then
  begin
    WriteLn( 'NetOpenSocket() failed: ', CoStatusToStr( Status ) );
    Exit;
  end;

  Status := Sock^.CoBind( nil, COF_PROPAGATE, nil );

  if Status <> CST_SUCCESS then
  begin
    WriteLn( 'CoBind() failed: ', Sock^.CoStatusToStr( Status ) );
    NetCloseSocket( Sock );
    Exit;
  end;

  DstAddr.Size    := SizeOf( DstAddr );
  DstAddr.Address := MakeIpAddr( 127, 0, 0, 1 );
  DstAddr.Port    := 5000;

  repeat

    WriteLn( 'Send' );

    Status := Sock^.CoSendBufferTo( @Buffer, SizeOf( Buffer ), 0, @DstAddr, nil );

    if Status <> CST_SUCCESS then
    begin
      WriteLn( 'CoSendBufferTo() failed: ', Sock^.CoStatusToStr( Status ) );
      Break;
    end;

    Status := Sock^.CoRecvBufferFrom( @Buffer, SizeOf( Buffer ), @RecvLen, 0, @SrcAddr, nil );

    if Status <> CST_SUCCESS then
    begin
      WriteLn( 'CoSendBufferFrom() failed: ', Sock^.CoStatusToStr( Status ) );
      Break;
    end
    else begin
      WriteLn( 'Received: ', RecvLen, ' bytes' );
    end;

  until Keypressed;

  ReadKey;


  Status := Sock^.CoUnbind( 0, nil );

  if Status <> CST_SUCCESS then
  begin
    WriteLn( 'CoUnbind() failed: ', Sock^.CoStatusToStr( Status ) );
  end;

  NetCloseSocket( Sock );

end;


var
  Status: TCoStatus;

begin
  WriteLn( 'MemAvail: ', MemAvail );
  WriteLn( 'Press any key' );
  ReadKey;


  { Otevreni TCP/IP stacku }

  Status := NetOpenStack( 'ETH01', 'IOBASE=$300',
             'IPADDR="192.168.1.210" REASMTO=5', '' );

  if Status <> CST_SUCCESS then
  begin
    WriteLn( 'NetOpenStack() failed: ', CoStatusToStr( Status ) );
    Exit;
  end;

  WriteLn( 'TCP/IP stack initialized' );

  { Spusteni testu }

  LoopbackTest;

  { Uzavreni TCP/IP stacku }

  NetCloseStack( '' );

  WriteLn( 'MemAvail: ', MemAvail );

end.