Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do socket programming in zig?

Tags:

sockets

zig

By looking at the docs of zig's standard library I found out that it actually does have some functions for socket programming. But I just don't know how to use them as they are not documented completely.

To create a socket, one can use std.os.socket() function which takes three arguments: domain, socket_type, protocol. They are all of type u32. Now I have done socket programming in Python. In python there are some predefined variables like socket.AF_INET and socket.SOCK_STREAM which you can use as argument for the socket.socket function which takes address_family and protocol arguments. But I couldn't find such variables in zig's docs so I don't know what should be the value of these arguments.

Also After defining the socket using os.socket() function, one can use os.bind() function which takes 3 arguments: sock, addr, len. obviously sock is the created socket but what should be supplied as address and length? I'm also baffled about os.accept() function. it takes addr, addr_size and flags arguments. I have no idea what values should go there too.

like image 951
Pexicade Avatar asked Sep 01 '25 01:09

Pexicade


1 Answers

file: client.zig

const std = @import("std");
const net = std.net;

const addr = net.Address.initIp4(.{ 127, 0, 0, 1 }, 7496);

pub fn eclient() !void {
    const options = net.StreamServer.Options{};
    var server = net.StreamServer.init(options);
    // Listening
    _ = try server.listen(addr);

    std.debug.print("Server is listening on: {any}\n", .{addr});
    while (true) {
        const client = try server.accept();
        const client_addr = client.address;
        const stream = client.stream;

        // Buffer for read
        var buffer: [256]u8 = undefined;

        _ = try stream.read(&buffer);
        _ = try stream.write("Hi there!");

        std.debug.print("client addr is : {any}\n", .{client_addr});
        std.debug.print("request buffer is : {s}\n", .{buffer});
    }
}

file: main.zig

const std = @import("std");
const client = @import("client.zig");

pub fn main() !void {
    const result = client.eclient();
    _ = try result;
}
like image 169
centi Avatar answered Sep 03 '25 09:09

centi