Skip to content
SocketAddrFormat

SocketAddrFormat

Description

Render a SocketAddr back into a “ip:port” string. IPv6 addresses are emitted with [...] brackets so the output round-trips through SocketAddrParse.

Parameters

Name Direction Description
addr in Address to format.
alloc in Allocator backing the returned Str. Caller owns the result and must StrDeinit it.

Success

returns initialized Str.

Failure

returns empty Str if the address cannot be formatted (e.g. unknown family); logs the failure.

Usage example (Cross-references)

Usage examples (Cross-references)
                return false;
            }
            Str rendered = SocketAddrFormat(&addr, alloc_base);
            ok           = ok && rendered.length > 0 && ZstrCompare(rendered.data, "127.0.0.1:8080") == 0;
            StrDeinit(&rendered);
                return false;
            }
            Str rendered = SocketAddrFormat(&addr, alloc_base);
            ok           = ok && rendered.length > 0 && ZstrCompare(rendered.data, "[::1]:8080") == 0;
            StrDeinit(&rendered);
    }
    
    Str SocketAddrFormat(const SocketAddr *addr, Allocator *alloc) {
        Str out = StrInit(alloc);
        if (!addr || addr->length == 0) {
            const struct sockaddr_in *sa = (const struct sockaddr_in *)addr->raw;
            if (!inet_ntop(AF_INET, &sa->sin_addr, host, sizeof(host))) {
                LOG_SYS_ERROR("SocketAddrFormat: inet_ntop(AF_INET) failed");
                return out;
            }
            const struct sockaddr_in6 *sa = (const struct sockaddr_in6 *)addr->raw;
            if (!inet_ntop(AF_INET6, &sa->sin6_addr, host, sizeof(host))) {
                LOG_SYS_ERROR("SocketAddrFormat: inet_ntop(AF_INET6) failed");
                return out;
            }
            StrWriteFmt(&out, "[{}]:{}", host_p, (u32)port);
        } else {
            LOG_ERROR("SocketAddrFormat: unknown family {}", (u32)addr->family);
        }
    
    static void handle_connection(Allocator *alloc, Socket *client, const SocketAddr *upstream_addr) {
        Str peer_str = SocketAddrFormat(&client->peer, alloc);
    
        Socket upstream;
Last updated on