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

Idiom #121 UDP listen and read

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

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($socket, '127.0.0.1', 1337);

socket_recvfrom($socket, $buffer, 16, 0, $fromAddr, $fromPort);
echo "[{$fromAddr}:{$fromPort}]\t{$buffer}";

// Send a test from the command line such as:
// echo "hello" > /dev/udp/127.0.0.1/1337
import std.socket;
ubyte[1024] b;

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

sock.bind(new InternetAddress(p));
sock.receive(b);
import (
    "fmt"
    "net"
    "os"
)
ServerAddr,err := net.ResolveUDPAddr("udp",p)
if err != nil {
	return err
}
ServerConn, err := net.ListenUDP("udp", ServerAddr)
if err != nil {
	return err
}
defer ServerConn.Close()
n,addr,err := ServerConn.ReadFromUDP(b[:1024])
if err != nil {
	return err
}
if n<1024 {
	return fmt.Errorf("Only %d bytes could be read.", n)
}
use std::net::UdpSocket;
let mut b = [0 as u8; 1024];
let sock = UdpSocket::bind(("localhost", p)).unwrap();
sock.recv_from(&mut b).unwrap();

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org