1 /*
2 * Copyright (c) 2001-2021 The strace developers.
3 * All rights reserved.
4 *
5 * SPDX-License-Identifier: LGPL-2.1-or-later
6 */
7
8 #include "defs.h"
9 #include <net/if.h>
10
11 #ifdef HAVE_IF_INDEXTONAME
12 # include "xstring.h"
13
14 # define INI_PFX "if_nametoindex(\""
15 # define INI_SFX "\")"
16 # define IFNAME_QUOTED_SZ (IFNAMSIZ * 4 + 3)
17
18 const char *
19 get_ifname(const unsigned int ifindex)
20 {
21 static char name_quoted_buf[IFNAME_QUOTED_SZ];
22 char name_buf[IFNAMSIZ];
23
24 if (!if_indextoname(ifindex, name_buf))
25 return NULL;
26
27 if (string_quote(name_buf, name_quoted_buf, sizeof(name_buf),
28 QUOTE_0_TERMINATED | QUOTE_OMIT_LEADING_TRAILING_QUOTES,
29 NULL))
30 return NULL;
31
32 return name_quoted_buf;
33 }
34
35 static const char *
36 sprint_ifname(const unsigned int ifindex)
37 {
38 static char res[IFNAME_QUOTED_SZ + sizeof(INI_PFX INI_SFX)];
39
40 const char *name_quoted = get_ifname(ifindex);
41
42 if (!name_quoted)
43 return NULL;
44
45 xsprintf(res, INI_PFX "%s" INI_SFX, name_quoted);
46
47 return res;
48 }
49
50 #else /* !HAVE_IF_INDEXTONAME */
51
52 const char *get_ifname(const unsigned int ifindex) { return NULL; }
53
54 #endif /* HAVE_IF_INDEXTONAME */
55
56 void
57 print_ifindex(const unsigned int ifindex)
58 {
59 #ifdef HAVE_IF_INDEXTONAME
60 print_xlat_ex(ifindex, sprint_ifname(ifindex), XLAT_STYLE_FMT_U);
61 #else
62 PRINT_VAL_U(ifindex);
63 #endif
64 }