ikkeniet has asked for the wisdom of the Perl Monks concerning the following question:

I am having difficulties in getting to workaround a code snippet that waits for a UDP packet to arrive. After some browsing I found out that the SIG{ALRM} does not work on Windows. Can someone point me out on how to achieve similar result on Windows (without dieing - if possible) Code snippet
$RECV_TIMEOUT=5; # obtient la réponse eval { local $SIG{ALRM} = sub { die "temporisation de l'a +larme" }; alarm $RECV_TIMEOUT; $portaddr = recv($sock, $packet, 1500, 0) or die " +Réception impossible: $!"; alarm 0; 1; } or die($@);

Replies are listed 'Best First'.
Re: Timeout on UDP receiving (Windows)
by BrowserUk (Patriarch) on Nov 02, 2008 at 12:30 UTC

    Season with error handling to taste:

    #! perl -slw use strict; use IO::Socket; $|++; sub recv_timeout { my( $socket, $timeout ) = @_; ## Set up a select vector for the scoket my $vin = ''; vec( $vin, fileno( $socket ), 1 ) = 1; ## Wait for $timeout seconds if( select( $vin, undef, undef, $timeout ) ) { ## Go fetch my $portaddr = recv( $socket, my($input), 1500, 0) or return; ## Read failed ## Who from my( $port, $addr ) = sockaddr_in( $portaddr ); $addr = join '.', unpack 'C4', $addr; return ( $addr, $port, $input ); } ## Timeout return; } my $server = IO::Socket::INET->new( LocalHost => 'localhost:54321', Proto => 'udp', Reuse => 1. ) or die $^E; ## Set socket non-blocking my $true = 1; ioctl( $server, 0x8004667e, \$true); while( 1 ) { if( my( $addr, $port, $input ) = recv_timeout( $server, 5 ) ) { print "\nGot '$input' from '$addr:$port'"; } printf '.'; }

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      BrowserUk: thanks for your code but I am unclear as that how I can integrate it within my code... Any clues or guidance?
Re: Timeout on UDP receiving (Windows)
by Corion (Patriarch) on Nov 02, 2008 at 09:06 UTC

    I haven't done it myself, but maybe you can use select or IO::Select to wait for an incoming packet with a timeout. I don't know if it works for UDP sockets though.