diff options
author | default <nobody@localhost> | 2023-12-27 12:54:38 +0100 |
---|---|---|
committer | default <nobody@localhost> | 2023-12-27 12:54:38 +0100 |
commit | bf435af788d387b3d97fd744e3b1f6a73795beb8 (patch) | |
tree | 6d193edd88ef3818bffd9278ddab0248e1108ef3 /xs_socket.h | |
parent | 94a6274a4682e72d1850fd84f1fc7d81c2a460b1 (diff) |
Backport from xs.
Diffstat (limited to 'xs_socket.h')
-rw-r--r-- | xs_socket.h | 43 |
1 files changed, 30 insertions, 13 deletions
diff --git a/xs_socket.h b/xs_socket.h index eea2f2d..ab67a6b 100644 --- a/xs_socket.h +++ b/xs_socket.h @@ -7,9 +7,13 @@ int xs_socket_timeout(int s, double rto, double sto); int xs_socket_server(const char *addr, const char *serv); FILE *xs_socket_accept(int rs); -xs_str *xs_socket_peername(int s); +int _xs_socket_peername(int s, char *buf, int buf_size); int xs_socket_connect(const char *addr, const char *serv); +#ifdef _XS_H +xs_str *xs_socket_peername(int s); +#endif + #ifdef XS_IMPLEMENTATION @@ -17,6 +21,9 @@ int xs_socket_connect(const char *addr, const char *serv); #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> +#include <string.h> +#include <stdlib.h> +#include <unistd.h> int xs_socket_timeout(int s, double rto, double sto) @@ -100,34 +107,28 @@ FILE *xs_socket_accept(int rs) } -xs_str *xs_socket_peername(int s) -/* returns the remote address as a string */ +int _xs_socket_peername(int s, char *buf, int buf_size) +/* fill the buffer with the socket peername */ { - xs_str *ip = NULL; struct sockaddr_storage addr; socklen_t slen = sizeof(addr); + const char *p = NULL; if (getpeername(s, (struct sockaddr *)&addr, &slen) != -1) { - char buf[1024]; - const char *p = NULL; - if (addr.ss_family == AF_INET) { struct sockaddr_in *sa = (struct sockaddr_in *)&addr; - p = inet_ntop(AF_INET, &sa->sin_addr, buf, sizeof(buf)); + p = inet_ntop(AF_INET, &sa->sin_addr, buf, buf_size); } else if (addr.ss_family == AF_INET6) { struct sockaddr_in6 *sa = (struct sockaddr_in6 *)&addr; - p = inet_ntop(AF_INET6, &sa->sin6_addr, buf, sizeof(buf)); + p = inet_ntop(AF_INET6, &sa->sin6_addr, buf, buf_size); } - - if (p != NULL) - ip = xs_str_new(p); } - return ip; + return p != NULL; } @@ -195,6 +196,22 @@ int xs_socket_connect(const char *addr, const char *serv) } +#ifdef _XS_H + +xs_str *xs_socket_peername(int s) +/* returns the remote address as a string */ +{ + char buf[2028]; + xs_str *p = NULL; + + if (_xs_socket_peername(s, buf, sizeof(buf))) + p = xs_str_new(buf); + + return p; +} + +#endif /* _XS_H */ + #endif /* XS_IMPLEMENTATION */ #endif /* _XS_SOCKET_H */ |