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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With