1 /* $NetBSD: ifconf.c,v 1.1 2014/12/08 04:23:03 ozaki-r Exp $ */
3 * Copyright (c) 2014 The NetBSD Foundation, Inc.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include <sys/cdefs.h>
28 __RCSID("$NetBSD: ifconf.c,v 1.1 2014/12/08 04:23:03 ozaki-r Exp $");
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <sys/sockio.h>
32 #include <sys/ioctl.h>
45 fprintf(stderr
, "usage:\n\t%s total\n\t%s list [<nifreqs>]\n",
46 getprogname(), getprogname());
51 get_number_of_entries(void)
56 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
58 err(EXIT_FAILURE
, "socket");
63 r
= ioctl(fd
, SIOCGIFCONF
, &ifc
);
65 err(EXIT_FAILURE
, "ioctl");
69 return ifc
.ifc_len
/ sizeof(struct ifreq
);
73 show_number_of_entries(void)
75 printf("%d\n", get_number_of_entries());
79 show_interfaces(int nifreqs
)
86 nifreqs
= get_number_of_entries();
89 errx(EXIT_FAILURE
, "nifreqs=%d", nifreqs
);
91 ifreqs
= malloc(sizeof(struct ifreq
) * nifreqs
);
93 err(EXIT_FAILURE
, "malloc(sizeof(ifreq) * %d)", nifreqs
);
95 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
97 err(EXIT_FAILURE
, "socket");
99 ifc
.ifc_len
= sizeof(struct ifreq
) * nifreqs
;
100 ifc
.ifc_req
= ifreqs
;
102 r
= ioctl(fd
, SIOCGIFCONF
, &ifc
);
104 err(EXIT_FAILURE
, "ioctl");
107 for (i
=0; i
< (int)(ifc
.ifc_len
/ sizeof(struct ifreq
)); i
++) {
108 printf("%s: af=%hhu socklen=%hhu\n", ifreqs
[i
].ifr_name
,
109 ifreqs
[i
].ifr_addr
.sa_family
, ifreqs
[i
].ifr_addr
.sa_len
);
116 main(int argc
, char *argv
[])
121 if (strcmp(argv
[1], "total") == 0) {
122 show_number_of_entries();
123 } else if (strcmp(argv
[1], "list") == 0) {
127 show_interfaces(atoi(argv
[2]));