Using the source address from std.posix.recvfrom and printing to string

Can’t seem to find much information on this. I want to print some telemetry for a simple chat client/server. Part of this “telemetry” is a list of addresses (so std.net.Address). I know how to get the data into the std.net.Address struct and where to access it, but can’t seem to find a way to put it into a string that doesn’t feel hacky.

Is there a painless way to convert that into something usable by std.debug.print? All the ways I’ve thought of doing this seem hacky, and then I I’m like, this feels like it’s likely something I shouldn’t need to make “in-house”.

More than happy to of course, but there are some wheels I would prefer not to re-invent :smile:.

std.net.Address knows how to format itself.

The following example:

const std = @import("std");

pub fn main() void {
    const addr = std.net.Address.initIp4([4]u8{ 8, 8, 8, 8 }, 43);
    std.debug.print("{}\n", .{addr});
}

prints: 8.8.8.8:43


You can print an array of addresses using any:
This example:

const std = @import("std");

pub fn main() void {
    const addresses = [_]std.net.Address{
        std.net.Address.initIp4([4]u8{ 8, 8, 8, 8 }, 43),
        std.net.Address.initIp4([4]u8{ 1, 1, 1, 1 }, 43),
    };
    std.debug.print("{any}\n", .{addresses});
}

prints: { 8.8.8.8:43, 1.1.1.1:43 }

4 Likes

How does it know how to print dotted notation for the addr? Is there a way to add print formatters to fmt for classes?

Any user defined type can implement a format method to specify how to print itself.

2 Likes

Is there any documentation on how to write a formation function, what the fmt field is (the unparsed version of the formatoptions?), can we add type specific options? what does the out_stream expect to have implemented?

Here’s an example Idiomatic Complex Formatting - #5 by castholm .

Long story short, the first parameter will be your struct type and the last parameter is just a normal writer. Those are the two you’l use pretry much always. The fmt and options parameters are usually just ignored.

1 Like