summaryrefslogtreecommitdiff
path: root/src/libstddjb/sagethostname.c
blob: 90108f808a9a062f6af18290da3840570038711e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* ISC license. */

#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <skalibs/stralloc.h>
#include <skalibs/djbunix.h>

int sagethostname (stralloc *sa)
{
  size_t n = 32 ;
  int e = errno ;
  int wasnull = !sa->s ;

  for (;;)
  {
    if (!stralloc_readyplus(sa, n)) goto err ;
    sa->s[sa->len + n - 2] = 0 ;
    errno = 0 ;
    if (gethostname(sa->s + sa->len, n) < 0)
    {
      if (errno != ENAMETOOLONG) goto err ;
    }
    else if (!sa->s[sa->len + n - 2]) break ;
    n += 32 ;
  }
  sa->len += strlen(sa->s + sa->len) ;
  errno = e ;
  return 0 ;

err:
  if (wasnull) stralloc_free(sa) ;
  return -1 ;
}