zig icon indicating copy to clipboard operation
zig copied to clipboard

Duplicate sockaddr structs.

Open vamuscari opened this issue 1 year ago • 4 comments

Zig Version

0.12.0

Steps to Reproduce and Observed Behavior

Hello! I have been having some issues the os.linux.socket to work.

Problem: The sockaddr struct is declared in std.os and std.posix. This causes a type conflict when binding to a port because the compiler thinks they are different structs.

(main.zig:14:30: error: expected type 'os.linux.sockaddr', found 'c.darwin.sockaddr')

I was uncertain if this was a skill issue so I did a diff to make sure that they are the same struct.

Here is the code that produces the issue:

const std = @import("std");
const net = std.net;
const os = std.os.linux;
const print = std.debug.print;

pub fn main() !void {
    const ip: []const u8 = "127.0.0.1";
    const port: u16 = 3000;
    const addr = try net.Address.parseIp4(ip, port);
    const sock: i32 = @intCast(os.socket(os.AF.INET, os.SOCK.DGRAM, 0));
    try os.bind(sock, addr.any, addr.getOsSockLen());
}

Expected Behavior

I would expect to not get this issue since they are exactly the same. I would imagine std.os should reference the std.posix?

vamuscari avatar May 14 '24 23:05 vamuscari

how did u call zig on the command line? what arch/os is your host?

nektro avatar May 15 '24 00:05 nektro

@nektro CLI Call: zig Arch: apple M3

vamuscari avatar May 15 '24 00:05 vamuscari

std.net.Address uses std.posix.sockaddr which is the correct type as it will change depending on the platform but youre unconditionally using std.os.linux. heres the version that compiles

const std = @import("std");
const net = std.net;
const posix = std.posix;
const print = std.debug.print;

pub fn main() !void {
    const ip: []const u8 = "127.0.0.1";
    const port: u16 = 3000;
    const addr = try net.Address.parseIp4(ip, port);
    const sock = try posix.socket(posix.AF.INET, posix.SOCK.DGRAM, 0);
    try posix.bind(sock, &addr.any, addr.getOsSockLen());
}

I would imagine std.os should reference the std.posix?

its the exact opposite, std.posix is an abstraction over different systems that implement posix so std.posix.foo will be std.os.linux.foo when targeting linux but std.c.darwin.foo when targeting macos

xdBronch avatar May 15 '24 00:05 xdBronch

@xdBronch Thank for the clarification!

There is one thing Im still unsure about though. I ended up in using std.net because I wanted to parse an address into a sockaddr struct. Is there a way to do this for the std.os.linux? or is it supposed to be used in a different way? I will just use the posix lib for simplicity, but what I intend on making will end on a linux server.

vamuscari avatar May 15 '24 02:05 vamuscari

If you write a program for Linux and want to compile it on MacOS you need to specify -target aarch64-linux.

Vexu avatar May 19 '24 16:05 Vexu