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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |