srctree

Gregory Mullen parent c78e39eb 6a470f4c
mv upstream server -> dns.zig & use in client

src/client.zig added: 38, removed: 22, total 16
@@ -16,10 +16,7 @@ pub fn main() !void {
}
}
 
const addr: std.net.Address = .{ .in = .{ .sa = .{
.port = std.mem.nativeToBig(u16, 53),
.addr = std.mem.bytesToValue(u32, &nameserver),
} } };
const upstream = try DNS.Upstream.init(nameserver);
 
const msg = try DNS.Message.query(a, &[1][]const u8{domain orelse "gr.ht."});
var request: [1024]u8 = undefined;
@@ -29,13 +26,10 @@ pub fn main() !void {
std.debug.print("data {any}\n", .{request[0..msgsize]});
std.debug.print("data {s}\n", .{request[0..msgsize]});
 
const sock = try std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM, 0);
try std.posix.connect(sock, &addr.any, addr.getOsSockLen());
const ocnt = try std.posix.send(sock, request[0..msgsize], 0);
std.debug.print("sent {}\n", .{ocnt});
try upstream.send(request[0..msgsize]);
 
var buffer: [1024]u8 = undefined;
const icnt = try std.posix.recv(sock, &buffer, 0);
const icnt = try upstream.recv(&buffer);
std.debug.print("received {}\n", .{icnt});
std.debug.print("data {any}\n", .{buffer[0..icnt]});
std.debug.print("data {s}\n", .{buffer[0..icnt]});
 
src/dns.zig added: 38, removed: 22, total 16
@@ -8,6 +8,36 @@ pub const Domains = struct {
),
};
 
pub const Upstream = struct {
addr: std.net.Address,
sock: std.posix.socket_t,
 
pub fn init(addr_ip: [4]u8) !Upstream {
const addr: std.net.Address = .{ .in = .{ .sa = .{
.port = nativeToBig(u16, 53),
.addr = bytesToValue(u32, &addr_ip),
} } };
const sock = try std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM, 0);
try std.posix.connect(sock, &addr.any, addr.getOsSockLen());
 
return .{
.addr = addr,
.sock = sock,
};
}
 
pub fn send(upstrm: Upstream, data: []const u8) !void {
const cnt = try std.posix.send(upstrm.sock, data, 0);
if (cnt != data.len) return error.TxFailed;
}
 
pub fn recv(upstrm: Upstream, buffer: []u8) !usize {
if (buffer.len < 512) return error.BufferTooSmall;
const icnt = try std.posix.recv(upstrm.sock, buffer, 0);
return icnt;
}
};
 
pub const Message = struct {
header: Header,
questions: ?[]Question = null,
@@ -422,3 +452,5 @@ const std = @import("std");
const log = std.log;
const Allocator = std.mem.Allocator;
const indexOfScalar = std.mem.indexOfScalar;
const nativeToBig = std.mem.nativeToBig;
const bytesToValue = std.mem.bytesToValue;
 
src/server.zig added: 38, removed: 22, total 16
@@ -43,16 +43,6 @@ pub fn main() !void {
std.debug.print("done\n", .{});
}
 
const Upstream = struct {
sock: std.posix.socket_t,
 
pub fn init() Upstream {
return .{
.sock = undefined,
};
}
};
 
const DNS = @import("dns.zig");
 
const std = @import("std");