Skip to content

ListenerOpen

Description

Open + bind + listen on the given address.

Parameters

Name Direction Description
out out Listener to populate. Untouched on failure.
kind in SOCKET_KIND_TCP (UDP listeners do not call listen() but the same entry point applies — see notes in the implementation).
addr in Address to bind to.
backlog in listen() backlog. Use 128 if you are unsure.

Success

returns true; out is ready for ListenerAccept.

Failure

returns false; logs the failing syscall.

Usage example (Cross-references)

Usage examples (Cross-references)
        }
    
        if (!ListenerOpen(&listener, SOCKET_KIND_TCP, &bind_addr, 16)) {
            return false;
        }
    // ---------------------------------------------------------------------------
    
    bool ListenerOpen(Listener *out, SocketKind kind, const SocketAddr *addr, i32 backlog) {
        if (!out || !addr) {
            LOG_ERROR("ListenerOpen: NULL argument");
    bool ListenerOpen(Listener *out, SocketKind kind, const SocketAddr *addr, i32 backlog) {
        if (!out || !addr) {
            LOG_ERROR("ListenerOpen: NULL argument");
            return false;
        }
        i32 proto    = sock_kind_to_protocol(kind);
        if (af == AF_UNSPEC || socktype < 0) {
            LOG_ERROR("ListenerOpen: invalid family/kind combination");
            return false;
        }
        i32 fd = socket(af, socktype, proto);
        if (fd < 0) {
            LOG_SYS_ERROR("ListenerOpen: socket() failed");
            return false;
        }
        i32 yes = 1;
        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0) {
            LOG_SYS_ERROR("ListenerOpen: setsockopt(SO_REUSEADDR) failed");
            close(fd);
            return false;
    
        if (bind(fd, (const struct sockaddr *)addr->raw, (socklen_t)addr->length) < 0) {
            LOG_SYS_ERROR("ListenerOpen: bind() failed");
            close(fd);
            return false;
        if (kind == SOCKET_KIND_TCP) {
            if (listen(fd, backlog > 0 ? backlog : 128) < 0) {
                LOG_SYS_ERROR("ListenerOpen: listen() failed");
                close(fd);
                return false;
    
            Listener listener;
            if (!ListenerOpen(&listener, SOCKET_KIND_TCP, &listen_addr, 128)) {
                LOG_ERROR("failed to open listener on {}", listen_spec);
                LogDeinit();
Last updated on