Socket module

to_string

procedure · 2 overloadsSource

Formats an IPv4 endpoint as address:port, such as 127.0.0.1:8080.

The port is read in network order and printed in decimal; the address is never resolved to a name. The result is allocated with context.allocator and the caller frees it.

Example
address: sockaddr_in;
address.sin_family = AF_INET;
address.sin_port = htons(8080);

#if OS == .WINDOWS address.sin_addr.S_un.S_addr = htonl(INADDR_LOOPBACK);
else address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

text := to_string(address);
defer free(text);

assert(text == "127.0.0.1:8080");

// An all-zero record is the unspecified address on port 0.
empty: sockaddr_in;
zero := to_string(empty);
defer free(zero);

assert(zero == "0.0.0.0:0");

Doesn't run in the browser (skipped on wasm).

to_string :: (addr: sockaddr_in) -> string

Formats an IPv4 endpoint as address:port, such as 127.0.0.1:8080.

The port is read in network order and printed in decimal; the address is never resolved to a name. The result is allocated with context.allocator and the caller frees it.

Parameters

addr: sockaddr_in

Returns

string
Example
address: sockaddr_in;
address.sin_family = AF_INET;
address.sin_port = htons(8080);

#if OS == .WINDOWS address.sin_addr.S_un.S_addr = htonl(INADDR_LOOPBACK);
else address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

text := to_string(address);
defer free(text);

assert(text == "127.0.0.1:8080");

// An all-zero record is the unspecified address on port 0.
empty: sockaddr_in;
zero := to_string(empty);
defer free(zero);

assert(zero == "0.0.0.0:0");

Doesn't run in the browser (skipped on wasm).

to_string :: (addr: sockaddr_in6) -> string

Formats an IPv6 endpoint as [address]:port, such as [::1]:443.

The address is written in the usual short form: lowercase hex groups without leading zeros, with the longest run of two or more zero groups (the first, when two are as long) shown as ::. The brackets keep the port apart from the address. An IPv4-mapped address prints as hex groups, not as dotted decimal. The scope id and flow label are not shown. The result is allocated with context.allocator and the caller frees it. append_address gives the eight groups in full instead.

Parameters

addr: sockaddr_in6

Returns

string
Example
address: sockaddr_in6;
address.sin6_family = AF_INET6;
address.sin6_port = htons(443);
bytes: [16] u8;
bytes[15] = 1;
memcpy(*address.sin6_addr, bytes.data, 16);

text := to_string(address);
defer free(text);

assert(text == "[::1]:443");

empty: sockaddr_in6;
zero := to_string(empty);
defer free(zero);

assert(zero == "[::]:0");

Doesn't run in the browser (skipped on wasm).

See also