UDP Socket Server in Zig

The following is a working example that wait for one packet, displays it and exits.

const std = @import("std");

pub fn main() !void {
    const addr = try std.net.Address.parseIp("127.0.0.1", 55555);
    const sock = try std.os.socket(std.os.AF.INET, std.os.SOCK.DGRAM, std.os.IPPROTO.UDP);
    defer std.os.close(sock);
    try std.os.bind(sock, &addr.any, addr.getOsSockLen());
    var buf: [1024]u8 = undefined;
    const len = try std.os.recv(sock, &buf, 0);
    std.debug.print("{s}\n", .{buf[0..len]});
}

EDIT: You can use recvfrom to get the IP address and port of the remote party.

6 Likes