Sockets / UDP

I’m trying to figure out how to listen for UDP data. I’ve looked through various examples which all seem to suggest os agnostic approaches using the std.os library. I presume this has changed since those examples were written, but I’m not sure how I should be doing this now.

The examples I’m seeing do things like:

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]});
}

As far as I can see, std.os.socket doesn’t exist but there are versions for each os i.e. std.os.linux.socket

I’ve tried doing something using the linux specific version

const sock = std.os.linux.socket(std.os.linux.AF.INET, std.os.linux.SOCK.DGRAM, 0);

instead of returning a socket_t though this returns a usize and as such can’t be passed into std.os.linux.bind as that requires an i32.

I’m sure I’m mixing things up, but not really sure where to go from here. Any help pointing me in the right direction would be really appreciated.

The code is using zig 0.11.0, in 0.12.0 std.os became std.posix.

The following code waits for a UDP message in port 55555, it displays the message and exits. If you want to implement a server, simply loop on recvfrom.

const std = @import("std");

pub fn main() !void {
    const sock = try std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM, std.posix.IPPROTO.UDP);
    defer std.posix.close(sock);

    const addr = try std.net.Address.parseIp("127.0.0.1", 55555);
    try std.posix.bind(sock, &addr.any, addr.getOsSockLen());

    var buf: [1024]u8 = undefined;
    const len = try std.posix.recvfrom(sock, &buf, 0, null, null);
    std.debug.print("recv: {s}\n", .{buf[0..len]});
}

The following code sends a message to upd port 55555:

echo "Hello World" | nc -u 127.0.0.1 55555
5 Likes

Ah fantastic, thanks, exactly what I needed.

That is great.
By the way, welcome back to the forum.

2 Likes

Hey @dimdim I posted your answer on stackoverflow and mentioned you in it. Just so it has a bit more visibility.

I’ve made it clear that the answer was from you and not me.

If it’s not okay, I can take it down. Do let me know.

1 Like

just use zig-network