Back to libut API Reference


    #include "libut/ut.h"
    int UT_net_listen(char *name, char *ipport, UT_fd_cb *cb, void *data);


This function establishes a listening TCP/IP socket having the given descriptive name on the IP address and port number specified in the ipport string. When connections are made to this listening socket, libut accepts them and invokes the callback cb with the opaque data pointer as an argument. The callback is also invoked whenever data is subsequently received. (See the CALLBACK section below).

The descriptive name (e.g. ``upload_port'') is used in the output of the fds control port command and in log messages. It is copied, and will be silently truncated if too long.

The ipport string must be formatted as a numeric dotted-quad IPv4 address followed by a colon and numeric port number, e.g., ``''. (A DNS hostname/port can be converted to an IP address/port using the function UT_net_resolve(3).) In order for the listening socket to be successfully created, the IP address must be bound to the machine on which the program is running and the port number must be obtainable.


The callback cb must have this prototype:

    int (UT_fd_cb)(int fd, char *name, int flags, void *data);

The callback receives the file descriptor fd of the connected socket, the descriptive name, status flags (see below) and the opaque data that were specified when the listening socket was created.

Acceptance of new connections

Libut automatically accepts new connections made to the listening socket, and notifies the callback of each new connection (prior to the arrival of any data from the remote side). Libut provides this notification by invoking the callback with the UTFD_IS_NEWACCEPT bit set in the flags.

Subsequent receipt of data on a connection

Subsequently, whenever data (or EOF) is received from the remote side, libut invokes the callback (without the UTFD_IS_NEWACCEPT bit set in the flags). The callback can read the data using the UNIX read(2) system call. Data can be written using UT_fd_write(3). (This is preferred over write(2) since it handles non-blocking draining of the buffer as the remote side is writable).

Closure of the connected socket

When the connection is no longer needed, or the callback detects that the remote side has closed its end of the socket, the callback should call close(2) and UT_fd_unreg(3) on the file descriptor fd.

Callback return value

The int value returned by the callback is ignored.


On success, the non-negative file descriptor of the listening socket is returned. On error, -1 is returned and the error text is written to the log.


The fds command displays listening as well as connected sockets.


UT_net_listen_close(3), UT_net_resolve(3)


Troy D. Hanson <>