Files
2026-09-29 20:42:04 +01:00

126 lines
2.9 KiB
C

#ifndef NX_SOCKADDR_H
#define NX_SOCKADDR_H
#include "nx_types.h"
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <string.h>
#if defined(__cplusplus)
extern "C" {
#endif
#if !defined(AF_UNIX) && defined(AF_LOCAL)
#define AF_UNIX AF_LOCAL
#endif
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
defined(__OpenBSD__) || defined(__DragonFly__)
#define NX_HAS_SA_LEN 1
#else
#define NX_HAS_SA_LEN 0
#endif
static inline socklen_t nx_sockaddr_len(const struct sockaddr *sa)
{
if (sa == NULL) {
return 0;
}
switch (sa->sa_family) {
case AF_INET:
return (socklen_t)sizeof(struct sockaddr_in);
case AF_INET6:
return (socklen_t)sizeof(struct sockaddr_in6);
#ifdef AF_UNIX
case AF_UNIX: {
const struct sockaddr_un *un = (const struct sockaddr_un *)(const void *)sa;
size_t path = strnlen(un->sun_path, sizeof(un->sun_path));
if (path == 0) {
return (socklen_t)sizeof(struct sockaddr_un);
}
return (socklen_t)(offsetof(struct sockaddr_un, sun_path) + path + 1);
}
#endif
default:
#if NX_HAS_SA_LEN
return (socklen_t)sa->sa_len;
#else
return (socklen_t)sizeof(struct sockaddr_storage);
#endif
}
}
static inline void nx_set_len(struct sockaddr *sa, socklen_t len)
{
#if NX_HAS_SA_LEN
sa->sa_len = (unsigned char)len;
#else
(void)sa;
(void)len;
#endif
}
static inline struct sockaddr_in *nx_sin(struct sockaddr *sa)
{
return (struct sockaddr_in *)(void *)sa;
}
static inline const struct sockaddr_in *nx_csin(const struct sockaddr *sa)
{
return (const struct sockaddr_in *)(const void *)sa;
}
static inline struct sockaddr_in6 *nx_sin6(struct sockaddr *sa)
{
return (struct sockaddr_in6 *)(void *)sa;
}
static inline const struct sockaddr_in6 *nx_csin6(const struct sockaddr *sa)
{
return (const struct sockaddr_in6 *)(const void *)sa;
}
static inline struct sockaddr_un *nx_sun(struct sockaddr *sa)
{
return (struct sockaddr_un *)(void *)sa;
}
static inline const struct sockaddr_un *nx_csun(const struct sockaddr *sa)
{
return (const struct sockaddr_un *)(const void *)sa;
}
static inline socklen_t nx_family_size(int family)
{
switch (family) {
case AF_INET:
return (socklen_t)sizeof(struct sockaddr_in);
case AF_INET6:
return (socklen_t)sizeof(struct sockaddr_in6);
default:
return 0;
}
}
int nx_addr_equal(const struct sockaddr *a, const struct sockaddr *b);
int nx_addr_format(const struct sockaddr *sa, char *buf, size_t len);
int nx_addr_port(const struct sockaddr *sa);
int nx_addr_is_loopback(const struct sockaddr *sa);
int nx_addr_parse(const char *host, int port, struct sockaddr_storage *out);
void nx_addr_set_port(struct sockaddr *sa, int port);
int nx_addr_parse_ip(const char *host, int port, struct sockaddr_storage *out);
#if defined(__cplusplus)
}
#endif
#endif