Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #121 UDP listen and read

Listen UDP traffic on port p and read 1024 bytes into the buffer b.

use IO::Socket::IP qw(SOCK_DGRAM);
my $p = 55555;
my $socket = IO::Socket::IP->new(
    LocalHost => 'localhost',
    LocalService => $p,
    Type => SOCK_DGRAM,
);
while () {
    $socket->read(my $B, 1024);
}

To verify the socket is operating, run `ss -anptu`.

To feed UDP traffic, use <https://nmap.org/ncat/>:
`ncat -u localhost 55555 < /dev/urandom`
import std.socket;
ubyte[1024] b;

auto sock = new UdpSocket();
scope(exit) sock.close;

sock.bind(new InternetAddress(p));
sock.receive(b);

New implementation...
< >
programming-idioms.org