[fpc-pascal] SOLVED fpSelect fails with UDP sockets?

Klaus Hartnegg hartnegg at gmx.de
Sun Apr 3 18:32:50 CEST 2016


It works with
   rc := fpSelect (sock+1, at FDS,nil,nil,5000);

I did not understand the description of the first argument in the docs, 
so I used the value from the sample, this was not a good idea.


For reference here is the source that works:

Uses
   UnixType, BaseUnix, Sockets;

procedure abort (reason:string);
begin
   writeln (reason);
   halt;
end;

var
   sock: cint;
   ladr : SockAddr;
   radr : SockAddr;
   adrlen: tSockLen;
   msg : string[255];
   FDS : Tfdset;
   rc  : cint;

begin
   sock := fpSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
   if sock = -1 then
      abort ('Error from fpSocket');

   ladr.sin_family      := AF_INET;
   ladr.sin_addr.s_addr := INADDR_ANY;
   ladr.sin_port        := htons(2000);
   rc := fpBind (sock, @ladr, sizeof(ladr));
   if rc <> 0 then
      abort ('Error from fpBind');

   adrlen := sizeof(radr);

   Fpfd_zero (FDS);
   FpFd_set (sock,FDS);
   rc := fpSelect (sock+1, at FDS,nil,nil,5000);
   writeln (rc);
   if rc = -1 then
      abort ('Error from fpSelect');
   if rc = 0 then
      abort ('timeout');

   rc := fpRecvFrom (sock, @msg[1], 255, 0 {flags}, @radr, @adrlen);
   if rc = -1 then
      abort ('Error from FpRecv');

   if rc > 255 then
      rc := 255;
   msg[0] := chr(rc);
   writeln (msg);
end.



And this is the sender:

Uses
   UnixType, BaseUnix, Sockets;

procedure abort (reason:string);
begin
   writeln (reason);
   halt;
end;

var
   sock: cint;
   sadr: {TInet}SockAddr;
   dadr: {TInet}SockAddr;
   adrlen: tSockLen;
   msg : string;
   rc  : cint;

begin
   sock := fpSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
   if sock = -1 then
      abort ('Error from fpSocket');

   sadr.sin_family      := AF_INET;
   sadr.sin_addr.s_addr := INADDR_ANY;
   sadr.sin_port        := 0; { auto-select }
   rc := fpBind (sock, @sadr, sizeof(sadr));
   if rc <> 0 then
      abort ('Error from fpBind');

   dadr.sin_family := AF_INET;
   dadr.sin_addr.s_bytes[1] := 127;
   dadr.sin_addr.s_bytes[2] := 0;
   dadr.sin_addr.s_bytes[2] := 0;
   dadr.sin_addr.s_bytes[2] := 1;
   dadr.sin_port   := htons(2000);
   adrlen := sizeof(dadr);

   msg := 'hello, world!';

   rc := fpSendTo (sock, @msg[1], length(msg), 0 {flags}, @dadr, adrlen);
   if rc = length(msg) then
      writeln ('ok');
end.



More information about the fpc-pascal mailing list