These inline functions will allow hostname lenght to vary per system,
which is significant because on some sysctl-based systems, gethostname()
doesn't write anything if the output buffer is too small. While
MAXHOSTNAMELEN is a good guess how long the name might be it is best to
try to get the value from sysconf(), and fallback to values provided in
headers when sysconf() does not work.
Reference:
http://cr.yp.to/docs/unixport.html
Reference:
http://h21007.www2.hp.com/portal/download/files/unprot/stk/solaris_stk/im...
Reference:
http://refspecs.linuxfoundation.org/LSB_4.0.0/LSB-Core-generic/LSB-Core-g...
Signed-off-by: Sami Kerola <kerolasa(a)iki.fi>
---
cronie_common.h | 38 ++++++++++++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
diff --git a/cronie_common.h b/cronie_common.h
index 4ce172e..87699af 100644
--- a/cronie_common.h
+++ b/cronie_common.h
@@ -20,6 +20,8 @@
#ifndef CRONIE_COMMON_H
#define CRONIE_COMMON_H
+#include <stdlib.h>
+
#ifndef __attribute__
# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8)
# define __attribute__(x) /* empty */
@@ -34,4 +36,40 @@
# define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
#endif
+static inline size_t get_hostname_max(void) {
+ size_t len = sysconf(_SC_HOST_NAME_MAX);
+
+ if (0 < len)
+ return len;
+#ifdef MAXHOSTNAMELEN
+ return MAXHOSTNAMELEN;
+#elif HOST_NAME_MAX
+ return HOST_NAME_MAX;
+#endif
+ return 64;
+}
+
+static inline char *alloc_hostname_array(void) {
+ char *array;
+ size_t sz = get_hostname_max() + 1;
+
+ array = malloc(sizeof (char) * sz);
+ while (!array) {
+ usleep(1000);
+ array = malloc(sizeof (char) * sz);
+ }
+ return array;
+}
+
+static inline char *xgethostname(void) {
+ char *name = alloc_hostname_array();
+ size_t sz = get_hostname_max();
+
+ if (gethostname(name, sz) != 0)
+ return NULL;
+
+ name[sz - 1] = '\0';
+ return name;
+}
+
#endif /* CRONIE_COMMON_H */
--
1.8.1.1