Logo

Programming-Idioms

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 the buffer b.

require 'socket'
require 'socket'

p = 4913
u1 = UDPSocket.new
u1.bind("127.0.0.1", p)
u1.send "message-to-self", 0, "127.0.0.1", p

b = u1.recvfrom(1024).first
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)
}
import java.net.DatagramSocket;
import java.net.DatagramPacket;
int len = 1024;
int p = 8888;
byte[] b = new byte[len];
try (DatagramSocket socket = new DatagramSocket(p)) {
  DatagramPacket packet = new DatagramPacket(b, len);
  socket.receive(packet);
}
$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
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);
}
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, p))
while True:
    data, addr = sock.recvfrom(1024)
    print("received message:", data)
use std::net::UdpSocket;
let mut b = [0 as u8; 1024];
let sock = UdpSocket::bind(("localhost", p)).unwrap();
sock.recv_from(&mut b).unwrap();

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