Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

udp broadcast

by oha (Friar)
on May 13, 2020 at 08:29 UTC ( #11116741=perlquestion: print w/replies, xml ) Need Help??

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

dear Monks,

I have a device which sends udp broadcasts as shown in the tcpdump below:

10:23:48.240377 IP 192.168.0.50.49153 > 192.168.0.255.4210: UDP, lengt +h 28
and I wrote the following:
use strict; use warnings; use IO::Socket; my $sock = IO::Socket::INET->new( Type => IO::Socket::SOCK_DGRAM, Proto => 'udp', PeerAddr => '192.168.0.255:4210', Broadcast => 1, ReuseAddr => 1, ); print inet_ntoa($sock->sockaddr()), ":", $sock->sockport(), "\n"; print inet_ntoa($sock->peeraddr()), ":", $sock->peerport(), "\n"; my $data; $sock->recv($data, 100) or die "$!"; print "«$data»\n";
which shows:
192.168.0.49:37550 192.168.0.255:4210
and then blocks forever, even tho tcpdump shows activity.

What am i doing wrong?

Replies are listed 'Best First'.
Re: udp broadcast
by haukex (Bishop) on May 13, 2020 at 09:08 UTC

    I think you don't need to set up all those options the way you did, the following is enough for me to recieve UDP broadcasts.

    use IO::Socket::INET; my $sock = IO::Socket::INET->new( Proto => 'udp', LocalPort => 4210 ); $sock->recv(my $data, 100) or die $!; print "<<$data>>\n";

    Test via echo "Hello World" | socat - UDP-DATAGRAM:255.255.255.255:4210,broadcast

    Of course, if you've got a firewall, it has to allow incoming UDP packets on that port.

      great! thanks!

      I'm still confused why this work this way, since 4210 is not the local port, but the broadcast port. nevertheless it works and i'm happy :)

        Glad to help!

        I'm still confused why this work this way, since 4210 is not the local port, but the broadcast port.

        It's the port you're listening on, on the local machine. (The sender is not necessarily sending from their port 4210, they may be sending from a random port, but their packets are addressed to port 4210 on the receiving side. Update: You can see this in the tcpdump output you showed: "192.168.0.50.49153 > 192.168.0.255.4210")

        BTW, if you want to get the address from which the packet was sent, you can call $sock->peerhost immediately after the recv.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11116741]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2022-01-24 17:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (64 votes). Check out past polls.

    Notices?