f50864232d12da2d027072021f72b73044af11eb
[gnulib.git] / tests / test-net_if.c
1 /* Test of <net/if.h> functions.
2    Copyright (C) 2010-2012 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Simon Josefsson <simon@josefsson.org>, 2010.  */
18
19 #include <config.h>
20
21 #include <net/if.h>
22
23 static struct if_nameindex ni;
24
25 /* We do not yet have replacements for if_* functions on systems that
26    lack a native <net/if.h>.  */
27 #if HAVE_NET_IF_H
28 # include "signature.h"
29 SIGNATURE_CHECK (if_freenameindex, void, (struct if_nameindex *));
30 SIGNATURE_CHECK (if_indextoname, char *, (unsigned int, char *));
31 SIGNATURE_CHECK (if_nameindex, struct if_nameindex *, (void));
32 SIGNATURE_CHECK (if_nametoindex, unsigned int, (const char *));
33 #endif
34
35 #include <stddef.h> /* NULL */
36 #include <stdio.h> /* fprintf */
37
38 int
39 main (int argc, char *argv[])
40 {
41 #if HAVE_NET_IF_H
42   struct if_nameindex *ifnp, *p;
43
44   p = ifnp = if_nameindex ();
45   if (ifnp == NULL)
46     {
47       fputs ("if_nameindex returned NULL\n", stderr);
48       return 1;
49     }
50
51   while (p->if_index)
52     {
53       unsigned int idx;
54       char buf[IF_NAMESIZE];
55       char *q;
56
57       if (argc > 1)
58         printf ("index %d name %s\n", p->if_index, p->if_name);
59
60       idx = if_nametoindex (p->if_name);
61       if (idx != p->if_index)
62         {
63           fprintf (stderr, "if_nametoindex (%s) = %d != %d\n",
64                    p->if_name, idx, p->if_index);
65           return 1;
66         }
67
68       q = if_indextoname (p->if_index, buf);
69       if (q == NULL)
70         {
71           fprintf (stderr, "if_indextoname (%d) returned NULL\n", p->if_index);
72           return 1;
73         }
74       if (q != buf)
75         {
76           fprintf (stderr, "if_indextoname (%d) buffer mismatch?\n",
77                    p->if_index);
78           return 1;
79         }
80       if (strcmp (p->if_name, q) != 0)
81         {
82           fprintf (stderr, "if_indextoname (%s) = %s ?!\n", p->if_name, q);
83           return 1;
84         }
85
86       p++;
87     }
88
89   if_freenameindex (ifnp);
90 #endif /* HAVE_NET_IF_H */
91
92   return !IF_NAMESIZE + ni.if_index + !!ni.if_name;
93 }