Trouble getting socket connection right

Hi, currently I’m trying to use sockets.
Here is my server code so far, but somehow I get an error in the bind function:

const std = @import("std");
const os = @import("os");

const PORT: u32 = 4905;

pub fn main() anyerror!void {
    //create UDP socket
    const socket_fd = try std.os.socket(std.os.AF.INET6, std.os.SOCK.DGRAM, 0);
    defer std.os.closeSocket(socket_fd);

    const sockaddr_in = std.os.sockaddr.in{
        .family = std.os.AF.INET6,
        .addr = 0, 
        .port = PORT,
    };

    std.debug.print("{s}\n", .{sockaddr_in});
    std.debug.print("len of socketaddr_in: {d}\n", .{@sizeOf(@TypeOf(sockaddr_in))});

    try std.os.bind(socket_fd, @ptrCast(*const std.os.sockaddr, &sockaddr_in), @sizeOf(@TypeOf(sockaddr_in)));
}

here is the stderr output:

in{ .len = 16, .family = 30, .port = 4905, .addr = 0, .zero = { 0, 0, 0, 0, 0, 0, 0, 0 } }
len of socketaddr_in: 16
thread 320354 panic: reached unreachable code
/opt/homebrew/Cellar/zig/0.9.1/lib/zig/std/os.zig:3137:23: 0x102219fcf in std.os.bind (ws_coap)
            .INVAL => unreachable, // invalid parameters
                      ^
.../src/main.zig:20:20: 0x102219997 in main (ws_coap)
    try std.os.bind(socket_fd, @ptrCast(*const std.os.sockaddr, &sockaddr_in), @sizeOf(@TypeOf(sockaddr_in)));
                   ^
/opt/homebrew/Cellar/zig/0.9.1/lib/zig/std/start.zig:561:37: 0x10221c983 in std.start.callMain (ws_coap)
            const result = root.main() catch |err| {
                                    ^
/opt/homebrew/Cellar/zig/0.9.1/lib/zig/std/start.zig:495:12: 0x10221a2bb in std.start.callMainWithArgs (ws_coap)
    return @call(.{ .modifier = .always_inline }, callMain, .{});
           ^
/opt/homebrew/Cellar/zig/0.9.1/lib/zig/std/start.zig:460:12: 0x10221a1e7 in std.start.main (ws_coap)
    return @call(.{ .modifier = .always_inline }, callMainWithArgs, .{ @intCast(usize, c_argc), c_argv, envp });
           ^
???:?:?: 0x10232908b in ??? (???)
???:?:?: 0x283bffffffffffff in ??? (???)
The following command terminated unexpectedly:
.../zig_CoAP && .../zig-out/bin/ws_coap
error: the following build command failed with exit code 1:
.../zig_CoAP/zig-cache/o/6d38d45d27e1a948c2bba5a5caf7f2f8/build
...

Leaving a code example link for you that may help you :slight_smile:

https://zig-by-example.github.io/tcp-connection.html

1 Like

thats great, thank you!

1 Like

Happy Zigging :slight_smile: