1/* Convert a struct hostent object to a string.
2 Copyright (C) 2016-2017 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
18
19#include <support/format_nss.h>
20
21#include <arpa/inet.h>
22#include <stdio.h>
23#include <support/support.h>
24#include <support/xmemstream.h>
25
26static int
27address_length (int family)
28{
29 switch (family)
30 {
31 case AF_INET:
32 return 4;
33 case AF_INET6:
34 return 16;
35 }
36 return -1;
37}
38
39char *
40support_format_hostent (struct hostent *h)
41{
42 if (h == NULL)
43 {
44 char *value = support_format_herrno (h_errno);
45 char *result = xasprintf ("error: %s\n", value);
46 free (value);
47 return result;
48 }
49
50 struct xmemstream mem;
51 xopen_memstream (&mem);
52
53 fprintf (mem.out, "name: %s\n", h->h_name);
54 for (char **alias = h->h_aliases; *alias != NULL; ++alias)
55 fprintf (mem.out, "alias: %s\n", *alias);
56 for (unsigned i = 0; h->h_addr_list[i] != NULL; ++i)
57 {
58 char buf[128];
59 if (inet_ntop (h->h_addrtype, h->h_addr_list[i],
60 buf, sizeof (buf)) == NULL)
61 fprintf (mem.out, "error: inet_ntop failed: %m\n");
62 else
63 fprintf (mem.out, "address: %s\n", buf);
64 }
65 if (h->h_length != address_length (h->h_addrtype))
66 {
67 char *family = support_format_address_family (h->h_addrtype);
68 fprintf (mem.out, "error: invalid address length %d for %s\n",
69 h->h_length, family);
70 free (family);
71 }
72
73 xfclose_memstream (&mem);
74 return mem.buffer;
75}
76