Mercurial > libjeffpc
changeset 803:32d261e8b47f
sock: add a way to get the hostname in a reliable way
This function never fails. If it encounters a failure, it simply returns
the "<unknown>" string.
Signed-off-by: Josef 'Jeff' Sipek <jeffpc@josefsipek.net>
author | Josef 'Jeff' Sipek <jeffpc@josefsipek.net> |
---|---|
date | Fri, 15 Mar 2019 11:42:40 -0400 |
parents | aa6e8f99966f |
children | 59316ed46006 |
files | include/jeffpc/sock.h mapfile-vers sock.c |
diffstat | 3 files changed, 47 insertions(+), 2 deletions(-) [+] |
line wrap: on
line diff
--- a/include/jeffpc/sock.h Thu Apr 09 12:15:48 2020 -0400 +++ b/include/jeffpc/sock.h Fri Mar 15 11:42:40 2019 -0400 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Josef 'Jeff' Sipek <jeffpc@josefsipek.net> + * Copyright (c) 2016-2019 Josef 'Jeff' Sipek <jeffpc@josefsipek.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -35,4 +35,6 @@ extern int connect_ip(const char *host, uint16_t port, bool v4, bool v6, enum ip_type type); +extern const char *xgethostname(void); + #endif
--- a/mapfile-vers Thu Apr 09 12:15:48 2020 -0400 +++ b/mapfile-vers Fri Mar 15 11:42:40 2019 -0400 @@ -238,6 +238,7 @@ # sock connect_ip; + xgethostname; # socksvc socksvc;
--- a/sock.c Thu Apr 09 12:15:48 2020 -0400 +++ b/sock.c Fri Mar 15 11:42:40 2019 -0400 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-2018 Josef 'Jeff' Sipek <jeffpc@josefsipek.net> + * Copyright (c) 2016-2019 Josef 'Jeff' Sipek <jeffpc@josefsipek.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -25,8 +25,50 @@ #include <unistd.h> #include <jeffpc/sock.h> +#include <jeffpc/atomic.h> #include <jeffpc/config.h> +const char *xgethostname(void) +{ + static const char *cached; + char *name; + ssize_t len; + int ret; + + if (cached) + return cached; + +#if defined(HOST_NAME_MAX) + len = HOST_NAME_MAX; +#elif defined(MAXHOSTNAMELEN) + len = MAXHOSTNAMELEN; +#else + len = sysconf(_SC_HOST_NAME_MAX); + if (len < 0) + goto unknown; +#endif + + len++; /* space for the trailing nul */ + + name = malloc(len); + if (!name) + goto unknown; + + ret = gethostname(name, len); + if (ret) { + free(name); + goto unknown; + } + + if (atomic_cas_ptr(&cached, NULL, name) != name) + free(name); + + return cached; + +unknown: + return "<unknown>"; +} + int connect_ip(const char *host, uint16_t port, bool v4, bool v6, enum ip_type type) { struct addrinfo hints, *res, *p;