I want to write simle udp server discovery. When I try this little example code with broadcast address, the Server receives the message and send out the answer but the client does not receive the reply. What is the problem? or the client broadcasted socket never receiving non-broadcasted messages?

#!/usr/bin/perl -w # !!! Client !!! use IO::Socket; use strict; my($sock, $server_host, $msg,$msg1, $port, $ipaddr, $hishost,$iaddr, $MAXLEN, $PORTNO, $TIMEOUT); $MAXLEN = 1024; $PORTNO = 5151; $server_host = '192.168.2.255'; $TIMEOUT = 5; $msg = "@ARGV"; my $sock1 = IO::Socket::INET->new( Proto => 'udp', PeerPort => 6543, PeerAddr => $server_host, Type => SOCK_DGRAM, Broadcast => 1 ) or die "Creating socket: $!\n"; $sock1->send($msg) or die "send: $!"; eval { local $SIG{ALRM} = sub {die "No response from server!\n"}; alarm 5; $sock1->recv($msg, $MAXLEN); print "Got \"$msg\" from server!\n"; alarm 0; 1; # Value for eval code block on normal exit. } or die "recv from $server_host timed out after $TIMEOUT second +s.\n";
#!/usr/bin/perl -w # !!! Server !!! use strict; use IO::Socket; my($sock, $oldmsg, $newmsg, $hisaddr, $hishost, $MAXLEN, $PORTNO); $MAXLEN = 1024; my $sock1 = IO::Socket::INET->new( LocalPort => 6543, Type => SOCK_DGRAM, Proto => 'udp' ) or die "socket: $@"; $oldmsg = "This is the starting message."; while ($sock->recv($newmsg, $MAXLEN)) { my($port, $ipaddr) = sockaddr_in($sock->peername); printf("%s\n",$sock->sockhost); printf("%s\n",$sock->peerhost); $hishost = gethostbyaddr($ipaddr, AF_INET); print "Client $hishost said ``$newmsg''\n"; $sock->send($oldmsg); $oldmsg = "[$hishost] $newmsg"; }

In reply to UDP Broadcast socket by kemenz

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.