Network
IPv4 socket helpers for listening over TCP and binding over UDP. Accepting connections, transferring data, and closing descriptors stays with the caller.
Usage#
lf_listen_tcp binds an IPv4 TCP socket and listens. lf_bind_udp binds an IPv4 UDP socket. A NULL host binds all local IPv4 interfaces. The port string is passed through to getaddrinfo; "0" asks the system for an ephemeral port. Close every descriptor the helper returns.
int tcp = lf_listen_tcp("127.0.0.1", "8080");
if (tcp >= 0) {
lf_close(tcp);
}
int udp = lf_bind_udp(NULL, "0");
if (udp >= 0) {
lf_close(udp);
}Functions#
lf_listen_tcp#
Creates an IPv4 TCP socket, binds it, and starts listening. Returns the socket descriptor, or -1 on error. port must be non-NULL. A NULL host binds INADDR_ANY. The helper requests SO_REUSEADDR before bind. The listen backlog is 5.
int lf_listen_tcp(const char *host, const char *port);lf_bind_udp#
Creates an IPv4 UDP socket and binds it. Returns the socket descriptor, or -1 on error. The host, port, and SO_REUSEADDR rules match lf_listen_tcp. It does not listen.
int lf_bind_udp(const char *host, const char *port);lf_close#
Closes fd if it is nonnegative. A negative descriptor does nothing.
void lf_close(int fd);get_in_addr#
Returns a pointer to the IPv4 or IPv6 address inside sa. The pointer borrows storage from sa. Returns NULL if sa is NULL or has an unsupported address family. This helper accepts IPv6 addresses even though the bind helpers only create IPv4 sockets.
void *get_in_addr(struct sockaddr *sa);