xref: /titanic_50/usr/src/cmd/cmd-inet/usr.bin/netstat/netstat.c (revision f9edfba4e2ac2531f0e52d0c4007976054e1023d)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * Copyright (c) 1990  Mentat Inc.
28  * netstat.c 2.2, last change 9/9/91
29  * MROUTING Revision 3.5
30  */
31 
32 #pragma ident	"%Z%%M%	%I%	%E% SMI"
33 
34 /*
35  * simple netstat based on snmp/mib-2 interface to the TCP/IP stack
36  *
37  * NOTES:
38  * 1. A comment "LINTED: (note 1)" appears before certain lines where
39  *    lint would have complained, "pointer cast may result in improper
40  *    alignment". These are lines where lint had suspected potential
41  *    improper alignment of a data structure; in each such situation
42  *    we have relied on the kernel guaranteeing proper alignment.
43  * 2. Some 'for' loops have been commented as "'for' loop 1", etc
44  *    because they have 'continue' or 'break' statements in their
45  *    bodies. 'continue' statements have been used inside some loops
46  *    where avoiding them would have led to deep levels of indentation.
47  *
48  * TODO:
49  *	Add ability to request subsets from kernel (with level = MIB2_IP;
50  *	name = 0 meaning everything for compatibility)
51  */
52 
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <stdarg.h>
56 #include <unistd.h>
57 #include <strings.h>
58 #include <string.h>
59 #include <errno.h>
60 #include <ctype.h>
61 #include <kstat.h>
62 #include <assert.h>
63 
64 #include <sys/types.h>
65 #include <sys/stream.h>
66 #include <stropts.h>
67 #include <sys/strstat.h>
68 #include <sys/tihdr.h>
69 
70 #include <sys/socket.h>
71 #include <sys/sockio.h>
72 #include <netinet/in.h>
73 #include <net/if.h>
74 #include <net/route.h>
75 
76 #include <inet/mib2.h>
77 #include <inet/ip.h>
78 #include <inet/arp.h>
79 #include <inet/tcp.h>
80 #include <netinet/igmp_var.h>
81 #include <netinet/ip_mroute.h>
82 
83 #include <arpa/inet.h>
84 #include <netdb.h>
85 #include <fcntl.h>
86 #include <sys/systeminfo.h>
87 #include <arpa/inet.h>
88 
89 #include <netinet/dhcp.h>
90 #include <dhcpagent_ipc.h>
91 #include <dhcpagent_util.h>
92 #include <compat.h>
93 
94 #include <libtsnet.h>
95 #include <tsol/label.h>
96 
97 extern void	unixpr(kstat_ctl_t *kc);
98 
99 #define	STR_EXPAND	4
100 
101 #define	V4MASK_TO_V6(v4, v6)	((v6)._S6_un._S6_u32[0] = 0xfffffffful, \
102 				(v6)._S6_un._S6_u32[1] = 0xfffffffful, \
103 				(v6)._S6_un._S6_u32[2] = 0xfffffffful, \
104 				(v6)._S6_un._S6_u32[3] = (v4))
105 
106 #define	IN6_IS_V4MASK(v6)	((v6)._S6_un._S6_u32[0] == 0xfffffffful && \
107 				(v6)._S6_un._S6_u32[1] == 0xfffffffful && \
108 				(v6)._S6_un._S6_u32[2] == 0xfffffffful)
109 
110 /*
111  * This is used as a cushion in the buffer allocation directed by SIOCGLIFNUM.
112  * Because there's no locking between SIOCGLIFNUM and SIOCGLIFCONF, it's
113  * possible for an administrator to plumb new interfaces between those two
114  * calls, resulting in the failure of the latter.  This addition makes that
115  * less likely.
116  */
117 #define	LIFN_GUARD_VALUE	10
118 
119 typedef struct mib_item_s {
120 	struct mib_item_s	*next_item;
121 	int			group;
122 	int			mib_id;
123 	int			length;
124 	void			*valp;
125 } mib_item_t;
126 
127 struct	ifstat {
128 	uint64_t	ipackets;
129 	uint64_t	ierrors;
130 	uint64_t	opackets;
131 	uint64_t	oerrors;
132 	uint64_t	collisions;
133 };
134 
135 struct iflist {
136 	struct iflist	*next_if;
137 	char		ifname[LIFNAMSIZ];
138 	struct ifstat	tot;
139 };
140 
141 static	mib_item_t	*mibget(int sd);
142 static	void		mibfree(mib_item_t *firstitem);
143 static	int		mibopen(void);
144 static void		mib_get_constants(mib_item_t *item);
145 static mib_item_t	*mib_item_dup(mib_item_t *item);
146 static mib_item_t	*mib_item_diff(mib_item_t *item1,
147     mib_item_t *item2);
148 static void		mib_item_destroy(mib_item_t **item);
149 
150 static boolean_t	octetstrmatch(const Octet_t *a, const Octet_t *b);
151 static char		*octetstr(const Octet_t *op, int code,
152 			    char *dst, uint_t dstlen);
153 static char		*pr_addr(uint_t addr,
154 			    char *dst, uint_t dstlen);
155 static char		*pr_addrnz(ipaddr_t addr, char *dst, uint_t dstlen);
156 static char		*pr_addr6(const in6_addr_t *addr,
157 			    char *dst, uint_t dstlen);
158 static char		*pr_mask(uint_t addr,
159 			    char *dst, uint_t dstlen);
160 static char		*pr_prefix6(const struct in6_addr *addr,
161 			    uint_t prefixlen, char *dst, uint_t dstlen);
162 static char		*pr_ap(uint_t addr, uint_t port,
163 			    char *proto, char *dst, uint_t dstlen);
164 static char		*pr_ap6(const in6_addr_t *addr, uint_t port,
165 			    char *proto, char *dst, uint_t dstlen);
166 static char		*pr_net(uint_t addr, uint_t mask,
167 			    char *dst, uint_t dstlen);
168 static char		*pr_netaddr(uint_t addr, uint_t mask,
169 			    char *dst, uint_t dstlen);
170 static char		*fmodestr(uint_t fmode);
171 static char		*portname(uint_t port, char *proto,
172 			    char *dst, uint_t dstlen);
173 
174 static const char	*mitcp_state(int code,
175 			    const mib2_transportMLPEntry_t *attr);
176 static const char	*miudp_state(int code,
177 			    const mib2_transportMLPEntry_t *attr);
178 
179 static void		stat_report(mib_item_t *item);
180 static void		mrt_stat_report(mib_item_t *item);
181 static void		arp_report(mib_item_t *item);
182 static void		ndp_report(mib_item_t *item);
183 static void		mrt_report(mib_item_t *item);
184 static void		if_stat_total(struct ifstat *oldstats,
185 			    struct ifstat *newstats, struct ifstat *sumstats);
186 static void		if_report(mib_item_t *item, char *ifname,
187 			    int Iflag_only, boolean_t once_only);
188 static void		if_report_ip4(mib2_ipAddrEntry_t *ap,
189 			    char ifname[], char logintname[],
190 			    struct ifstat *statptr, boolean_t ksp_not_null);
191 static void		if_report_ip6(mib2_ipv6AddrEntry_t *ap6,
192 			    char ifname[], char logintname[],
193 			    struct ifstat *statptr, boolean_t ksp_not_null);
194 static void		ire_report(const mib_item_t *item);
195 static void		tcp_report(const mib_item_t *item);
196 static void		udp_report(const mib_item_t *item);
197 static void		group_report(mib_item_t *item);
198 static void		print_ip_stats(mib2_ip_t *ip);
199 static void		print_icmp_stats(mib2_icmp_t *icmp);
200 static void		print_ip6_stats(mib2_ipv6IfStatsEntry_t *ip6);
201 static void		print_icmp6_stats(mib2_ipv6IfIcmpEntry_t *icmp6);
202 static void		print_sctp_stats(mib2_sctp_t *tcp);
203 static void		print_tcp_stats(mib2_tcp_t *tcp);
204 static void		print_udp_stats(mib2_udp_t *udp);
205 static void		print_rawip_stats(mib2_rawip_t *rawip);
206 static void		print_igmp_stats(struct igmpstat *igps);
207 static void		print_mrt_stats(struct mrtstat *mrts);
208 static void		sctp_report(const mib_item_t *item);
209 static void		sum_ip6_stats(mib2_ipv6IfStatsEntry_t *ip6,
210 			    mib2_ipv6IfStatsEntry_t *sum6);
211 static void		sum_icmp6_stats(mib2_ipv6IfIcmpEntry_t *icmp6,
212 			    mib2_ipv6IfIcmpEntry_t *sum6);
213 static void		m_report(void);
214 static void		dhcp_report(char *);
215 
216 	void		fail(int, char *, ...);
217 static	uint64_t	kstat_named_value(kstat_t *, char *);
218 static	kid_t		safe_kstat_read(kstat_ctl_t *, kstat_t *, void *);
219 static int		isnum(char *);
220 static char		*plural(int n);
221 static char		*pluraly(int n);
222 static char		*plurales(int n);
223 static void		process_filter(char *arg);
224 static boolean_t	family_selected(int family);
225 
226 static void		usage(char *);
227 static void 		fatal(int errcode, char *str1, ...);
228 
229 #define	PLURAL(n) plural((int)n)
230 #define	PLURALY(n) pluraly((int)n)
231 #define	PLURALES(n) plurales((int)n)
232 #define	IFLAGMOD(flg, val1, val2)	if (flg == val1) flg = val2
233 #define	MDIFF(diff, elem2, elem1, member)	(diff)->member = \
234 	(elem2)->member - (elem1)->member
235 
236 
237 static	boolean_t	Aflag = B_FALSE;	/* All sockets/ifs/rtng-tbls */
238 static	boolean_t	Dflag = B_FALSE;	/* Debug Info */
239 static	boolean_t	Iflag = B_FALSE;	/* IP Traffic Interfaces */
240 static	boolean_t	Mflag = B_FALSE;	/* STREAMS Memory Statistics */
241 static	boolean_t	Nflag = B_FALSE;	/* Numeric Network Addresses */
242 static	boolean_t	Rflag = B_FALSE;	/* Routing Tables */
243 static	boolean_t	RSECflag = B_FALSE;	/* Security attributes */
244 static	boolean_t	Sflag = B_FALSE;	/* Per-protocol Statistics */
245 static	boolean_t	Vflag = B_FALSE;	/* Verbose */
246 static	boolean_t	Pflag = B_FALSE;	/* Net to Media Tables */
247 static	boolean_t	Gflag = B_FALSE;	/* Multicast group membership */
248 static	boolean_t	MMflag = B_FALSE;	/* Multicast routing table */
249 static	boolean_t	DHCPflag = B_FALSE;	/* DHCP statistics */
250 
251 static	int	v4compat = 0;	/* Compatible printing format for status */
252 
253 static int	proto = IPPROTO_MAX;	/* all protocols */
254 kstat_ctl_t	*kc = NULL;
255 
256 /*
257  * Sizes of data structures extracted from the base mib.
258  * This allows the size of the tables entries to grow while preserving
259  * binary compatibility.
260  */
261 static int ipAddrEntrySize;
262 static int ipRouteEntrySize;
263 static int ipNetToMediaEntrySize;
264 static int ipMemberEntrySize;
265 static int ipGroupSourceEntrySize;
266 static int ipRouteAttributeSize;
267 static int vifctlSize;
268 static int mfcctlSize;
269 
270 static int ipv6IfStatsEntrySize;
271 static int ipv6IfIcmpEntrySize;
272 static int ipv6AddrEntrySize;
273 static int ipv6RouteEntrySize;
274 static int ipv6NetToMediaEntrySize;
275 static int ipv6MemberEntrySize;
276 static int ipv6GroupSourceEntrySize;
277 
278 static int transportMLPSize;
279 static int tcpConnEntrySize;
280 static int tcp6ConnEntrySize;
281 static int udpEntrySize;
282 static int udp6EntrySize;
283 static int sctpEntrySize;
284 static int sctpLocalEntrySize;
285 static int sctpRemoteEntrySize;
286 
287 #define	protocol_selected(p)	(proto == IPPROTO_MAX || proto == (p))
288 
289 /* Machinery used for -f (filter) option */
290 enum { FK_AF = 0, FK_OUTIF, FK_DST, FK_FLAGS, NFILTERKEYS };
291 
292 static const char *filter_keys[NFILTERKEYS] = {
293 	"af", "outif", "dst", "flags"
294 };
295 
296 /* Flags on routes */
297 #define	FLF_A		0x00000001
298 #define	FLF_B		0x00000002
299 #define	FLF_D		0x00000004
300 #define	FLF_G		0x00000008
301 #define	FLF_H		0x00000010
302 #define	FLF_L		0x00000020
303 #define	FLF_U		0x00000040
304 #define	FLF_M		0x00000080
305 #define	FLF_S		0x00000100
306 static const char flag_list[] = "ABDGHLUMS";
307 
308 typedef struct filter_rule filter_t;
309 
310 struct filter_rule {
311 	filter_t *f_next;
312 	union {
313 		int f_family;
314 		const char *f_ifname;
315 		struct {
316 			struct hostent *f_address;
317 			in6_addr_t f_mask;
318 		} a;
319 		struct {
320 			uint_t f_flagset;
321 			uint_t f_flagclear;
322 		} f;
323 	} u;
324 };
325 
326 /*
327  * The user-specified filters are linked into lists separated by
328  * keyword (type of filter).  Thus, the matching algorithm is:
329  *	For each non-empty filter list
330  *		If no filters in the list match
331  *			then stop here; route doesn't match
332  *	If loop above completes, then route does match and will be
333  *	displayed.
334  */
335 static filter_t *filters[NFILTERKEYS];
336 
337 int
338 main(int argc, char **argv)
339 {
340 	char		*name;
341 	mib_item_t	*item = NULL;
342 	mib_item_t	*previtem = NULL;
343 	int		sd = -1;
344 	char	*ifname = NULL;
345 	int	interval = 0;	/* Single time by default */
346 	int	count = -1;	/* Forever */
347 	int	c;
348 	int	d;
349 	/*
350 	 * Possible values of 'Iflag_only':
351 	 * -1, no feature-flags;
352 	 *  0, IFlag and other feature-flags enabled
353 	 *  1, IFlag is the only feature-flag enabled
354 	 * : trinary variable, modified using IFLAGMOD()
355 	 */
356 	int Iflag_only = -1;
357 	boolean_t once_only = B_FALSE; /* '-i' with count > 1 */
358 	extern char	*optarg;
359 	extern int	optind;
360 	char *default_ip_str = NULL;
361 
362 	name = argv[0];
363 
364 	v4compat = get_compat_flag(&default_ip_str);
365 	if (v4compat == DEFAULT_PROT_BAD_VALUE)
366 		fatal(2, "%s: %s: Bad value for %s in %s\n", name,
367 		    default_ip_str, DEFAULT_IP, INET_DEFAULT_FILE);
368 	free(default_ip_str);
369 
370 	while ((c = getopt(argc, argv, "adimnrspMgvf:P:I:DR")) != -1) {
371 		switch ((char)c) {
372 		case 'a':		/* all connections */
373 			Aflag = B_TRUE;
374 			break;
375 
376 		case 'd':		/* turn on debugging */
377 			Dflag = B_TRUE;
378 			break;
379 
380 		case 'i':		/* interface (ill/ipif report) */
381 			Iflag = B_TRUE;
382 			IFLAGMOD(Iflag_only, -1, 1); /* '-i' exists */
383 			break;
384 
385 		case 'm':		/* streams msg report */
386 			Mflag = B_TRUE;
387 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
388 			break;
389 
390 		case 'n':		/* numeric format */
391 			Nflag = B_TRUE;
392 			break;
393 
394 		case 'r':		/* route tables */
395 			Rflag = B_TRUE;
396 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
397 			break;
398 
399 		case 'R':		/* security attributes */
400 			RSECflag = B_TRUE;
401 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
402 			break;
403 
404 		case 's':		/* per-protocol statistics */
405 			Sflag = B_TRUE;
406 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
407 			break;
408 
409 		case 'p':		/* arp/ndp table */
410 			Pflag = B_TRUE;
411 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
412 			break;
413 
414 		case 'M':		/* multicast routing tables */
415 			MMflag = B_TRUE;
416 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
417 			break;
418 
419 		case 'g':		/* multicast group membership */
420 			Gflag = B_TRUE;
421 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
422 			break;
423 
424 		case 'v':		/* verbose output format */
425 			Vflag = B_TRUE;
426 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
427 			break;
428 
429 		case 'f':
430 			process_filter(optarg);
431 			break;
432 
433 		case 'P':
434 			if (strcmp(optarg, "ip") == 0) {
435 				proto = IPPROTO_IP;
436 			} else if (strcmp(optarg, "ipv6") == 0 ||
437 			    strcmp(optarg, "ip6") == 0) {
438 				v4compat = 0;	/* Overridden */
439 				proto = IPPROTO_IPV6;
440 			} else if (strcmp(optarg, "icmp") == 0) {
441 				proto = IPPROTO_ICMP;
442 			} else if (strcmp(optarg, "icmpv6") == 0 ||
443 			    strcmp(optarg, "icmp6") == 0) {
444 				v4compat = 0;	/* Overridden */
445 				proto = IPPROTO_ICMPV6;
446 			} else if (strcmp(optarg, "igmp") == 0) {
447 				proto = IPPROTO_IGMP;
448 			} else if (strcmp(optarg, "udp") == 0) {
449 				proto = IPPROTO_UDP;
450 			} else if (strcmp(optarg, "tcp") == 0) {
451 				proto = IPPROTO_TCP;
452 			} else if (strcmp(optarg, "sctp") == 0) {
453 				proto = IPPROTO_SCTP;
454 			} else if (strcmp(optarg, "raw") == 0 ||
455 			    strcmp(optarg, "rawip") == 0) {
456 				proto = IPPROTO_RAW;
457 			} else {
458 				fatal(1, "%s: unknown protocol.\n", optarg);
459 			}
460 			break;
461 
462 		case 'I':
463 			ifname = optarg;
464 			Iflag = B_TRUE;
465 			IFLAGMOD(Iflag_only, -1, 1); /* see macro def'n */
466 			break;
467 
468 		case 'D':
469 			DHCPflag = B_TRUE;
470 			Iflag_only = 0;
471 			break;
472 
473 		case '?':
474 		default:
475 			usage(name);
476 		}
477 	}
478 
479 	/*
480 	 * Make sure -R option is set only on a labeled system.
481 	 */
482 	if (RSECflag && !is_system_labeled()) {
483 		(void) fprintf(stderr, "-R set but labeling is not enabled\n");
484 		usage(name);
485 	}
486 
487 	/*
488 	 * Handle other arguments: find interval, count; the
489 	 * flags that accept 'interval' and 'count' are OR'd
490 	 * in the outermost 'if'; more flags may be added as
491 	 * required
492 	 */
493 	if (Iflag || Sflag || Mflag) {
494 		for (d = optind; d < argc; d++) {
495 			if (isnum(argv[d])) {
496 				interval = atoi(argv[d]);
497 				if (d + 1 < argc &&
498 				    isnum(argv[d + 1])) {
499 					count = atoi(argv[d + 1]);
500 					optind++;
501 				}
502 				optind++;
503 				if (interval == 0 || count == 0)
504 					usage(name);
505 				break;
506 			}
507 		}
508 	}
509 	if (optind < argc) {
510 		if (Iflag && isnum(argv[optind])) {
511 			count = atoi(argv[optind]);
512 			if (count == 0)
513 				usage(name);
514 			optind++;
515 		}
516 	}
517 	if (optind < argc) {
518 		(void) fprintf(stderr,
519 		    "%s: extra arguments\n", name);
520 		usage(name);
521 	}
522 	if (interval)
523 		setbuf(stdout, NULL);
524 
525 	if (DHCPflag) {
526 		dhcp_report(Iflag ? ifname : NULL);
527 		exit(0);
528 	}
529 
530 	/* Get data structures: priming before iteration */
531 	if (family_selected(AF_INET) || family_selected(AF_INET6)) {
532 		sd = mibopen();
533 		if (sd == -1)
534 			fatal(1, "can't open mib stream\n");
535 		if ((item = mibget(sd)) == NULL) {
536 			(void) close(sd);
537 			fatal(1, "mibget() failed\n");
538 		}
539 		/* Extract constant sizes - need do once only */
540 		mib_get_constants(item);
541 	}
542 	if ((kc = kstat_open()) == NULL) {
543 		mibfree(item);
544 		(void) close(sd);
545 		fail(1, "kstat_open(): can't open /dev/kstat");
546 	}
547 
548 	if (interval <= 0) {
549 		count = 1;
550 		once_only = B_TRUE;
551 	}
552 	/* 'for' loop 1: */
553 	for (;;) {
554 		mib_item_t *curritem = NULL; /* only for -[M]s */
555 
556 		/* netstat: AF_INET[6] behaviour */
557 		if (family_selected(AF_INET) || family_selected(AF_INET6)) {
558 			if (Sflag) {
559 				curritem = mib_item_diff(previtem, item);
560 				if (curritem == NULL)
561 					fatal(1, "can't process mib data, "
562 					    "out of memory\n");
563 				mib_item_destroy(&previtem);
564 			}
565 
566 			if (!(Iflag || Rflag || Sflag || Mflag ||
567 			    MMflag || Pflag || Gflag || DHCPflag)) {
568 				if (protocol_selected(IPPROTO_UDP))
569 					udp_report(item);
570 				if (protocol_selected(IPPROTO_TCP))
571 					tcp_report(item);
572 				if (protocol_selected(IPPROTO_SCTP))
573 					sctp_report(item);
574 			}
575 			if (Iflag)
576 				if_report(item, ifname, Iflag_only, once_only);
577 			if (Mflag)
578 				m_report();
579 			if (Rflag)
580 				ire_report(item);
581 			if (Sflag && MMflag) {
582 				mrt_stat_report(curritem);
583 			} else {
584 				if (Sflag)
585 					stat_report(curritem);
586 				if (MMflag)
587 					mrt_report(item);
588 			}
589 			if (Gflag)
590 				group_report(item);
591 			if (Pflag) {
592 				if (family_selected(AF_INET))
593 					arp_report(item);
594 				if (family_selected(AF_INET6))
595 					ndp_report(item);
596 			}
597 			mib_item_destroy(&curritem);
598 		}
599 
600 		/* netstat: AF_UNIX behaviour */
601 		if (family_selected(AF_UNIX) &&
602 		    (!(Iflag || Rflag || Sflag || Mflag ||
603 		    MMflag || Pflag || Gflag)))
604 			unixpr(kc);
605 		(void) kstat_close(kc);
606 
607 		/* iteration handling code */
608 		if (count > 0 && --count == 0)
609 			break;
610 		(void) sleep(interval);
611 
612 		/* re-populating of data structures */
613 		if (family_selected(AF_INET) || family_selected(AF_INET6)) {
614 			if (Sflag) {
615 				/* previtem is a cut-down list */
616 				previtem = mib_item_dup(item);
617 				if (previtem == NULL)
618 					fatal(1, "can't process mib data, "
619 					    "out of memory\n");
620 			}
621 			mibfree(item);
622 			(void) close(sd);
623 			if ((sd = mibopen()) == -1)
624 				fatal(1, "can't open mib stream anymore\n");
625 			if ((item = mibget(sd)) == NULL) {
626 				(void) close(sd);
627 				fatal(1, "mibget() failed\n");
628 			}
629 		}
630 		if ((kc = kstat_open()) == NULL)
631 			fail(1, "kstat_open(): can't open /dev/kstat");
632 
633 	} /* 'for' loop 1 ends */
634 	mibfree(item);
635 	(void) close(sd);
636 
637 	return (0);
638 }
639 
640 
641 static int
642 isnum(char *p)
643 {
644 	int	len;
645 	int	i;
646 
647 	len = strlen(p);
648 	for (i = 0; i < len; i++)
649 		if (!isdigit(p[i]))
650 			return (0);
651 	return (1);
652 }
653 
654 
655 /* --------------------------------- MIBGET -------------------------------- */
656 
657 static mib_item_t *
658 mibget(int sd)
659 {
660 	/*
661 	 * buf is an automatic for this function, so the
662 	 * compiler has complete control over its alignment;
663 	 * it is assumed this alignment is satisfactory for
664 	 * it to be casted to certain other struct pointers
665 	 * here, such as struct T_optmgmt_ack * .
666 	 */
667 	uintptr_t		buf[512 / sizeof (uintptr_t)];
668 	int			flags;
669 	int			i, j, getcode;
670 	struct strbuf		ctlbuf, databuf;
671 	struct T_optmgmt_req	*tor = (struct T_optmgmt_req *)buf;
672 	struct T_optmgmt_ack	*toa = (struct T_optmgmt_ack *)buf;
673 	struct T_error_ack	*tea = (struct T_error_ack *)buf;
674 	struct opthdr		*req;
675 	mib_item_t		*first_item = NULL;
676 	mib_item_t		*last_item  = NULL;
677 	mib_item_t		*temp;
678 
679 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
680 	tor->OPT_offset = sizeof (struct T_optmgmt_req);
681 	tor->OPT_length = sizeof (struct opthdr);
682 	tor->MGMT_flags = T_CURRENT;
683 	req = (struct opthdr *)&tor[1];
684 	req->level = MIB2_IP;		/* any MIB2_xxx value ok here */
685 	req->name  = 0;
686 	req->len   = 0;
687 
688 	ctlbuf.buf = (char *)buf;
689 	ctlbuf.len = tor->OPT_length + tor->OPT_offset;
690 	flags = 0;
691 	if (putmsg(sd, &ctlbuf, (struct strbuf *)0, flags) == -1) {
692 		perror("mibget: putmsg(ctl) failed");
693 		goto error_exit;
694 	}
695 
696 	/*
697 	 * Each reply consists of a ctl part for one fixed structure
698 	 * or table, as defined in mib2.h.  The format is a T_OPTMGMT_ACK,
699 	 * containing an opthdr structure.  level/name identify the entry,
700 	 * len is the size of the data part of the message.
701 	 */
702 	req = (struct opthdr *)&toa[1];
703 	ctlbuf.maxlen = sizeof (buf);
704 	j = 1;
705 	for (;;) {
706 		flags = 0;
707 		getcode = getmsg(sd, &ctlbuf, (struct strbuf *)0, &flags);
708 		if (getcode == -1) {
709 			perror("mibget getmsg(ctl) failed");
710 			if (Dflag) {
711 				(void) fputs("#   level   name    len\n",
712 				    stderr);
713 				i = 0;
714 				for (last_item = first_item; last_item;
715 					last_item = last_item->next_item)
716 					(void) printf("%d  %4d   %5d   %d\n",
717 					    ++i,
718 					    last_item->group,
719 					    last_item->mib_id,
720 					    last_item->length);
721 			}
722 			goto error_exit;
723 		}
724 		if (getcode == 0 &&
725 		    ctlbuf.len >= sizeof (struct T_optmgmt_ack) &&
726 		    toa->PRIM_type == T_OPTMGMT_ACK &&
727 		    toa->MGMT_flags == T_SUCCESS &&
728 		    req->len == 0) {
729 			if (Dflag)
730 				(void) printf("mibget getmsg() %d returned "
731 				    "EOD (level %ld, name %ld)\n",
732 				    j, req->level, req->name);
733 			return (first_item);		/* this is EOD msg */
734 		}
735 
736 		if (ctlbuf.len >= sizeof (struct T_error_ack) &&
737 		    tea->PRIM_type == T_ERROR_ACK) {
738 			(void) fprintf(stderr,
739 			    "mibget %d gives T_ERROR_ACK: TLI_error = 0x%lx, "
740 			    "UNIX_error = 0x%lx\n",
741 			    j, tea->TLI_error, tea->UNIX_error);
742 
743 			errno = (tea->TLI_error == TSYSERR) ?
744 			    tea->UNIX_error : EPROTO;
745 			goto error_exit;
746 		}
747 
748 		if (getcode != MOREDATA ||
749 		    ctlbuf.len < sizeof (struct T_optmgmt_ack) ||
750 		    toa->PRIM_type != T_OPTMGMT_ACK ||
751 		    toa->MGMT_flags != T_SUCCESS) {
752 			(void) printf("mibget getmsg(ctl) %d returned %d, "
753 			    "ctlbuf.len = %d, PRIM_type = %ld\n",
754 			    j, getcode, ctlbuf.len, toa->PRIM_type);
755 
756 			if (toa->PRIM_type == T_OPTMGMT_ACK)
757 				(void) printf("T_OPTMGMT_ACK: "
758 				    "MGMT_flags = 0x%lx, req->len = %ld\n",
759 				    toa->MGMT_flags, req->len);
760 			errno = ENOMSG;
761 			goto error_exit;
762 		}
763 
764 		temp = (mib_item_t *)malloc(sizeof (mib_item_t));
765 		if (temp == NULL) {
766 			perror("mibget malloc failed");
767 			goto error_exit;
768 		}
769 		if (last_item != NULL)
770 			last_item->next_item = temp;
771 		else
772 			first_item = temp;
773 		last_item = temp;
774 		last_item->next_item = NULL;
775 		last_item->group = req->level;
776 		last_item->mib_id = req->name;
777 		last_item->length = req->len;
778 		last_item->valp = malloc((int)req->len);
779 		if (last_item->valp == NULL)
780 			goto error_exit;
781 		if (Dflag)
782 			(void) printf("msg %d: group = %4d   mib_id = %5d"
783 			    "length = %d\n",
784 			    j, last_item->group, last_item->mib_id,
785 			    last_item->length);
786 
787 		databuf.maxlen = last_item->length;
788 		databuf.buf    = (char *)last_item->valp;
789 		databuf.len    = 0;
790 		flags = 0;
791 		getcode = getmsg(sd, (struct strbuf *)0, &databuf, &flags);
792 		if (getcode == -1) {
793 			perror("mibget getmsg(data) failed");
794 			goto error_exit;
795 		} else if (getcode != 0) {
796 			(void) printf("mibget getmsg(data) returned %d, "
797 			    "databuf.maxlen = %d, databuf.len = %d\n",
798 			    getcode, databuf.maxlen, databuf.len);
799 			goto error_exit;
800 		}
801 		j++;
802 	}
803 	/* NOTREACHED */
804 
805 error_exit:;
806 	mibfree(first_item);
807 	return (NULL);
808 }
809 
810 /*
811  * mibfree: frees a linked list of type (mib_item_t *)
812  * returned by mibget(); this is NOT THE SAME AS
813  * mib_item_destroy(), so should be used for objects
814  * returned by mibget() only
815  */
816 static void
817 mibfree(mib_item_t *firstitem)
818 {
819 	mib_item_t *lastitem;
820 
821 	while (firstitem != NULL) {
822 		lastitem = firstitem;
823 		firstitem = firstitem->next_item;
824 		if (lastitem->valp != NULL)
825 			free(lastitem->valp);
826 		free(lastitem);
827 	}
828 }
829 
830 static int
831 mibopen(void)
832 {
833 	int	sd;
834 
835 	sd = open("/dev/arp", O_RDWR);
836 	if (sd == -1) {
837 		perror("arp open");
838 		return (-1);
839 	}
840 	if (ioctl(sd, I_PUSH, "tcp") == -1) {
841 		perror("tcp I_PUSH");
842 		(void) close(sd);
843 		return (-1);
844 	}
845 	if (ioctl(sd, I_PUSH, "udp") == -1) {
846 		perror("udp I_PUSH");
847 		(void) close(sd);
848 		return (-1);
849 	}
850 	if (ioctl(sd, I_PUSH, "icmp") == -1) {
851 		perror("icmp I_PUSH");
852 		(void) close(sd);
853 		return (-1);
854 	}
855 	return (sd);
856 }
857 
858 /*
859  * mib_item_dup: returns a clean mib_item_t * linked
860  * list, so that for every element item->mib_id is 0;
861  * to deallocate this linked list, use mib_item_destroy
862  */
863 static mib_item_t *
864 mib_item_dup(mib_item_t *item)
865 {
866 	int	c = 0;
867 	mib_item_t *localp;
868 	mib_item_t *tempp;
869 
870 	for (tempp = item; tempp; tempp = tempp->next_item)
871 		if (tempp->mib_id == 0)
872 			c++;
873 	tempp = NULL;
874 
875 	localp = (mib_item_t *)malloc(c * sizeof (mib_item_t));
876 	if (localp == NULL)
877 		return (NULL);
878 	c = 0;
879 	for (; item; item = item->next_item) {
880 		if (item->mib_id == 0) {
881 			/* Replicate item in localp */
882 			(localp[c]).next_item = NULL;
883 			(localp[c]).group = item->group;
884 			(localp[c]).mib_id = item->mib_id;
885 			(localp[c]).length = item->length;
886 			(localp[c]).valp = (uintptr_t *)malloc(
887 			    item->length);
888 			if ((localp[c]).valp == NULL) {
889 				mib_item_destroy(&localp);
890 				return (NULL);
891 			}
892 			(void *) memcpy((localp[c]).valp,
893 			    item->valp,
894 			    item->length);
895 			tempp = &(localp[c]);
896 			if (c > 0)
897 				(localp[c - 1]).next_item = tempp;
898 			c++;
899 		}
900 	}
901 	return (localp);
902 }
903 
904 /*
905  * mib_item_diff: takes two (mib_item_t *) linked lists
906  * item1 and item2 and computes the difference between
907  * differentiable values in item2 against item1 for every
908  * given member of item2; returns an mib_item_t * linked
909  * list of diff's, or a copy of item2 if item1 is NULL;
910  * will return NULL if system out of memory; works only
911  * for item->mib_id == 0
912  */
913 static mib_item_t *
914 mib_item_diff(mib_item_t *item1, mib_item_t *item2) {
915 	int	nitems	= 0; /* no. of items in item2 */
916 	mib_item_t *tempp2;  /* walking copy of item2 */
917 	mib_item_t *tempp1;  /* walking copy of item1 */
918 	mib_item_t *diffp;
919 	mib_item_t *diffptr; /* walking copy of diffp */
920 	mib_item_t *prevp = NULL;
921 
922 	if (item1 == NULL) {
923 		diffp = mib_item_dup(item2);
924 		return (diffp);
925 	}
926 
927 	for (tempp2 = item2;
928 	    tempp2;
929 	    tempp2 = tempp2->next_item) {
930 		if (tempp2->mib_id == 0)
931 			switch (tempp2->group) {
932 			/*
933 			 * upon adding a case here, the same
934 			 * must also be added in the next
935 			 * switch statement, alongwith
936 			 * appropriate code
937 			 */
938 			case MIB2_IP:
939 			case MIB2_IP6:
940 			case EXPER_DVMRP:
941 			case EXPER_IGMP:
942 			case MIB2_ICMP:
943 			case MIB2_ICMP6:
944 			case MIB2_TCP:
945 			case MIB2_UDP:
946 			case MIB2_SCTP:
947 			case EXPER_RAWIP:
948 				nitems++;
949 			}
950 	}
951 	tempp2 = NULL;
952 	if (nitems == 0) {
953 		diffp = mib_item_dup(item2);
954 		return (diffp);
955 	}
956 
957 	diffp = (mib_item_t *)calloc(nitems, sizeof (mib_item_t));
958 	if (diffp == NULL)
959 		return (NULL);
960 	diffptr = diffp;
961 	/* 'for' loop 1: */
962 	for (tempp2 = item2; tempp2 != NULL; tempp2 = tempp2->next_item) {
963 		if (tempp2->mib_id != 0)
964 			continue; /* 'for' loop 1 */
965 		/* 'for' loop 2: */
966 		for (tempp1 = item1; tempp1 != NULL;
967 		    tempp1 = tempp1->next_item) {
968 			if (!(tempp1->mib_id == 0 &&
969 			    tempp1->group == tempp2->group &&
970 			    tempp1->mib_id == tempp2->mib_id))
971 				continue; /* 'for' loop 2 */
972 			/* found comparable data sets */
973 			if (prevp != NULL)
974 				prevp->next_item = diffptr;
975 			switch (tempp2->group) {
976 			/*
977 			 * Indenting note: Because of long variable names
978 			 * in cases MIB2_IP6 and MIB2_ICMP6, their contents
979 			 * have been indented by one tab space only
980 			 */
981 			case MIB2_IP: {
982 				mib2_ip_t *i2 = (mib2_ip_t *)tempp2->valp;
983 				mib2_ip_t *i1 = (mib2_ip_t *)tempp1->valp;
984 				mib2_ip_t *d;
985 
986 				diffptr->group = tempp2->group;
987 				diffptr->mib_id = tempp2->mib_id;
988 				diffptr->length = tempp2->length;
989 				d = (mib2_ip_t *)calloc(tempp2->length, 1);
990 				if (d == NULL)
991 					goto mibdiff_out_of_memory;
992 				diffptr->valp = d;
993 				d->ipForwarding = i2->ipForwarding;
994 				d->ipDefaultTTL = i2->ipDefaultTTL;
995 				MDIFF(d, i2, i1, ipInReceives);
996 				MDIFF(d, i2, i1, ipInHdrErrors);
997 				MDIFF(d, i2, i1, ipInAddrErrors);
998 				MDIFF(d, i2, i1, ipInCksumErrs);
999 				MDIFF(d, i2, i1, ipForwDatagrams);
1000 				MDIFF(d, i2, i1, ipForwProhibits);
1001 				MDIFF(d, i2, i1, ipInUnknownProtos);
1002 				MDIFF(d, i2, i1, ipInDiscards);
1003 				MDIFF(d, i2, i1, ipInDelivers);
1004 				MDIFF(d, i2, i1, ipOutRequests);
1005 				MDIFF(d, i2, i1, ipOutDiscards);
1006 				MDIFF(d, i2, i1, ipOutNoRoutes);
1007 				MDIFF(d, i2, i1, ipReasmTimeout);
1008 				MDIFF(d, i2, i1, ipReasmReqds);
1009 				MDIFF(d, i2, i1, ipReasmOKs);
1010 				MDIFF(d, i2, i1, ipReasmFails);
1011 				MDIFF(d, i2, i1, ipReasmDuplicates);
1012 				MDIFF(d, i2, i1, ipReasmPartDups);
1013 				MDIFF(d, i2, i1, ipFragOKs);
1014 				MDIFF(d, i2, i1, ipFragFails);
1015 				MDIFF(d, i2, i1, ipFragCreates);
1016 				MDIFF(d, i2, i1, ipRoutingDiscards);
1017 				MDIFF(d, i2, i1, tcpInErrs);
1018 				MDIFF(d, i2, i1, udpNoPorts);
1019 				MDIFF(d, i2, i1, udpInCksumErrs);
1020 				MDIFF(d, i2, i1, udpInOverflows);
1021 				MDIFF(d, i2, i1, rawipInOverflows);
1022 				MDIFF(d, i2, i1, ipsecInSucceeded);
1023 				MDIFF(d, i2, i1, ipsecInFailed);
1024 				MDIFF(d, i2, i1, ipInIPv6);
1025 				MDIFF(d, i2, i1, ipOutIPv6);
1026 				MDIFF(d, i2, i1, ipOutSwitchIPv6);
1027 				prevp = diffptr++;
1028 				break;
1029 			}
1030 			case MIB2_IP6: {
1031 			mib2_ipv6IfStatsEntry_t *i2;
1032 			mib2_ipv6IfStatsEntry_t *i1;
1033 			mib2_ipv6IfStatsEntry_t *d;
1034 
1035 			i2 = (mib2_ipv6IfStatsEntry_t *)tempp2->valp;
1036 			i1 = (mib2_ipv6IfStatsEntry_t *)tempp1->valp;
1037 			diffptr->group = tempp2->group;
1038 			diffptr->mib_id = tempp2->mib_id;
1039 			diffptr->length = tempp2->length;
1040 			d = (mib2_ipv6IfStatsEntry_t *)calloc(
1041 			    tempp2->length, 1);
1042 			if (d == NULL)
1043 				goto mibdiff_out_of_memory;
1044 			diffptr->valp = d;
1045 			d->ipv6Forwarding = i2->ipv6Forwarding;
1046 			d->ipv6DefaultHopLimit =
1047 			    i2->ipv6DefaultHopLimit;
1048 
1049 			MDIFF(d, i2, i1, ipv6InReceives);
1050 			MDIFF(d, i2, i1, ipv6InHdrErrors);
1051 			MDIFF(d, i2, i1, ipv6InTooBigErrors);
1052 			MDIFF(d, i2, i1, ipv6InNoRoutes);
1053 			MDIFF(d, i2, i1, ipv6InAddrErrors);
1054 			MDIFF(d, i2, i1, ipv6InUnknownProtos);
1055 			MDIFF(d, i2, i1, ipv6InTruncatedPkts);
1056 			MDIFF(d, i2, i1, ipv6InDiscards);
1057 			MDIFF(d, i2, i1, ipv6InDelivers);
1058 			MDIFF(d, i2, i1, ipv6OutForwDatagrams);
1059 			MDIFF(d, i2, i1, ipv6OutRequests);
1060 			MDIFF(d, i2, i1, ipv6OutDiscards);
1061 			MDIFF(d, i2, i1, ipv6OutNoRoutes);
1062 			MDIFF(d, i2, i1, ipv6OutFragOKs);
1063 			MDIFF(d, i2, i1, ipv6OutFragFails);
1064 			MDIFF(d, i2, i1, ipv6OutFragCreates);
1065 			MDIFF(d, i2, i1, ipv6ReasmReqds);
1066 			MDIFF(d, i2, i1, ipv6ReasmOKs);
1067 			MDIFF(d, i2, i1, ipv6ReasmFails);
1068 			MDIFF(d, i2, i1, ipv6InMcastPkts);
1069 			MDIFF(d, i2, i1, ipv6OutMcastPkts);
1070 			MDIFF(d, i2, i1, ipv6ReasmDuplicates);
1071 			MDIFF(d, i2, i1, ipv6ReasmPartDups);
1072 			MDIFF(d, i2, i1, ipv6ForwProhibits);
1073 			MDIFF(d, i2, i1, udpInCksumErrs);
1074 			MDIFF(d, i2, i1, udpInOverflows);
1075 			MDIFF(d, i2, i1, rawipInOverflows);
1076 			MDIFF(d, i2, i1, ipv6InIPv4);
1077 			MDIFF(d, i2, i1, ipv6OutIPv4);
1078 			MDIFF(d, i2, i1, ipv6OutSwitchIPv4);
1079 			prevp = diffptr++;
1080 			break;
1081 			}
1082 			case EXPER_DVMRP: {
1083 				struct mrtstat *m2;
1084 				struct mrtstat *m1;
1085 				struct mrtstat *d;
1086 
1087 				m2 = (struct mrtstat *)tempp2->valp;
1088 				m1 = (struct mrtstat *)tempp1->valp;
1089 				diffptr->group = tempp2->group;
1090 				diffptr->mib_id = tempp2->mib_id;
1091 				diffptr->length = tempp2->length;
1092 				d = (struct mrtstat *)calloc(tempp2->length, 1);
1093 				if (d == NULL)
1094 					goto mibdiff_out_of_memory;
1095 				diffptr->valp = d;
1096 				MDIFF(d, m2, m1, mrts_mfc_hits);
1097 				MDIFF(d, m2, m1, mrts_mfc_misses);
1098 				MDIFF(d, m2, m1, mrts_fwd_in);
1099 				MDIFF(d, m2, m1, mrts_fwd_out);
1100 				d->mrts_upcalls = m2->mrts_upcalls;
1101 				MDIFF(d, m2, m1, mrts_fwd_drop);
1102 				MDIFF(d, m2, m1, mrts_bad_tunnel);
1103 				MDIFF(d, m2, m1, mrts_cant_tunnel);
1104 				MDIFF(d, m2, m1, mrts_wrong_if);
1105 				MDIFF(d, m2, m1, mrts_upq_ovflw);
1106 				MDIFF(d, m2, m1, mrts_cache_cleanups);
1107 				MDIFF(d, m2, m1, mrts_drop_sel);
1108 				MDIFF(d, m2, m1, mrts_q_overflow);
1109 				MDIFF(d, m2, m1, mrts_pkt2large);
1110 				MDIFF(d, m2, m1, mrts_pim_badversion);
1111 				MDIFF(d, m2, m1, mrts_pim_rcv_badcsum);
1112 				MDIFF(d, m2, m1, mrts_pim_badregisters);
1113 				MDIFF(d, m2, m1, mrts_pim_regforwards);
1114 				MDIFF(d, m2, m1, mrts_pim_regsend_drops);
1115 				MDIFF(d, m2, m1, mrts_pim_malformed);
1116 				MDIFF(d, m2, m1, mrts_pim_nomemory);
1117 				prevp = diffptr++;
1118 				break;
1119 			}
1120 			case EXPER_IGMP: {
1121 				struct igmpstat *i2;
1122 				struct igmpstat *i1;
1123 				struct igmpstat *d;
1124 
1125 				i2 = (struct igmpstat *)tempp2->valp;
1126 				i1 = (struct igmpstat *)tempp1->valp;
1127 				diffptr->group = tempp2->group;
1128 				diffptr->mib_id = tempp2->mib_id;
1129 				diffptr->length = tempp2->length;
1130 				d = (struct igmpstat *)calloc(
1131 				    tempp2->length, 1);
1132 				if (d == NULL)
1133 					goto mibdiff_out_of_memory;
1134 				diffptr->valp = d;
1135 				MDIFF(d, i2, i1, igps_rcv_total);
1136 				MDIFF(d, i2, i1, igps_rcv_tooshort);
1137 				MDIFF(d, i2, i1, igps_rcv_badsum);
1138 				MDIFF(d, i2, i1, igps_rcv_queries);
1139 				MDIFF(d, i2, i1, igps_rcv_badqueries);
1140 				MDIFF(d, i2, i1, igps_rcv_reports);
1141 				MDIFF(d, i2, i1, igps_rcv_badreports);
1142 				MDIFF(d, i2, i1, igps_rcv_ourreports);
1143 				MDIFF(d, i2, i1, igps_snd_reports);
1144 				prevp = diffptr++;
1145 				break;
1146 			}
1147 			case MIB2_ICMP: {
1148 				mib2_icmp_t *i2;
1149 				mib2_icmp_t *i1;
1150 				mib2_icmp_t *d;
1151 
1152 				i2 = (mib2_icmp_t *)tempp2->valp;
1153 				i1 = (mib2_icmp_t *)tempp1->valp;
1154 				diffptr->group = tempp2->group;
1155 				diffptr->mib_id = tempp2->mib_id;
1156 				diffptr->length = tempp2->length;
1157 				d = (mib2_icmp_t *)calloc(tempp2->length, 1);
1158 				if (d == NULL)
1159 					goto mibdiff_out_of_memory;
1160 				diffptr->valp = d;
1161 				MDIFF(d, i2, i1, icmpInMsgs);
1162 				MDIFF(d, i2, i1, icmpInErrors);
1163 				MDIFF(d, i2, i1, icmpInCksumErrs);
1164 				MDIFF(d, i2, i1, icmpInUnknowns);
1165 				MDIFF(d, i2, i1, icmpInDestUnreachs);
1166 				MDIFF(d, i2, i1, icmpInTimeExcds);
1167 				MDIFF(d, i2, i1, icmpInParmProbs);
1168 				MDIFF(d, i2, i1, icmpInSrcQuenchs);
1169 				MDIFF(d, i2, i1, icmpInRedirects);
1170 				MDIFF(d, i2, i1, icmpInBadRedirects);
1171 				MDIFF(d, i2, i1, icmpInEchos);
1172 				MDIFF(d, i2, i1, icmpInEchoReps);
1173 				MDIFF(d, i2, i1, icmpInTimestamps);
1174 				MDIFF(d, i2, i1, icmpInAddrMasks);
1175 				MDIFF(d, i2, i1, icmpInAddrMaskReps);
1176 				MDIFF(d, i2, i1, icmpInFragNeeded);
1177 				MDIFF(d, i2, i1, icmpOutMsgs);
1178 				MDIFF(d, i2, i1, icmpOutDrops);
1179 				MDIFF(d, i2, i1, icmpOutErrors);
1180 				MDIFF(d, i2, i1, icmpOutDestUnreachs);
1181 				MDIFF(d, i2, i1, icmpOutTimeExcds);
1182 				MDIFF(d, i2, i1, icmpOutParmProbs);
1183 				MDIFF(d, i2, i1, icmpOutSrcQuenchs);
1184 				MDIFF(d, i2, i1, icmpOutRedirects);
1185 				MDIFF(d, i2, i1, icmpOutEchos);
1186 				MDIFF(d, i2, i1, icmpOutEchoReps);
1187 				MDIFF(d, i2, i1, icmpOutTimestamps);
1188 				MDIFF(d, i2, i1, icmpOutTimestampReps);
1189 				MDIFF(d, i2, i1, icmpOutAddrMasks);
1190 				MDIFF(d, i2, i1, icmpOutAddrMaskReps);
1191 				MDIFF(d, i2, i1, icmpOutFragNeeded);
1192 				MDIFF(d, i2, i1, icmpInOverflows);
1193 				prevp = diffptr++;
1194 				break;
1195 			}
1196 			case MIB2_ICMP6: {
1197 	mib2_ipv6IfIcmpEntry_t *i2;
1198 	mib2_ipv6IfIcmpEntry_t *i1;
1199 	mib2_ipv6IfIcmpEntry_t *d;
1200 
1201 	i2 = (mib2_ipv6IfIcmpEntry_t *)tempp2->valp;
1202 	i1 = (mib2_ipv6IfIcmpEntry_t *)tempp1->valp;
1203 	diffptr->group = tempp2->group;
1204 	diffptr->mib_id = tempp2->mib_id;
1205 	diffptr->length = tempp2->length;
1206 	d = (mib2_ipv6IfIcmpEntry_t *)calloc(tempp2->length, 1);
1207 	if (d == NULL)
1208 		goto mibdiff_out_of_memory;
1209 	diffptr->valp = d;
1210 	MDIFF(d, i2, i1, ipv6IfIcmpInMsgs);
1211 	MDIFF(d, i2, i1, ipv6IfIcmpInErrors);
1212 	MDIFF(d, i2, i1, ipv6IfIcmpInDestUnreachs);
1213 	MDIFF(d, i2, i1, ipv6IfIcmpInAdminProhibs);
1214 	MDIFF(d, i2, i1, ipv6IfIcmpInTimeExcds);
1215 	MDIFF(d, i2, i1, ipv6IfIcmpInParmProblems);
1216 	MDIFF(d, i2, i1, ipv6IfIcmpInPktTooBigs);
1217 	MDIFF(d, i2, i1, ipv6IfIcmpInEchos);
1218 	MDIFF(d, i2, i1, ipv6IfIcmpInEchoReplies);
1219 	MDIFF(d, i2, i1, ipv6IfIcmpInRouterSolicits);
1220 	MDIFF(d, i2, i1, ipv6IfIcmpInRouterAdvertisements);
1221 	MDIFF(d, i2, i1, ipv6IfIcmpInNeighborSolicits);
1222 	MDIFF(d, i2, i1, ipv6IfIcmpInNeighborAdvertisements);
1223 	MDIFF(d, i2, i1, ipv6IfIcmpInRedirects);
1224 	MDIFF(d, i2, i1, ipv6IfIcmpInBadRedirects);
1225 	MDIFF(d, i2, i1, ipv6IfIcmpInGroupMembQueries);
1226 	MDIFF(d, i2, i1, ipv6IfIcmpInGroupMembResponses);
1227 	MDIFF(d, i2, i1, ipv6IfIcmpInGroupMembReductions);
1228 	MDIFF(d, i2, i1, ipv6IfIcmpInOverflows);
1229 	MDIFF(d, i2, i1, ipv6IfIcmpOutMsgs);
1230 	MDIFF(d, i2, i1, ipv6IfIcmpOutErrors);
1231 	MDIFF(d, i2, i1, ipv6IfIcmpOutDestUnreachs);
1232 	MDIFF(d, i2, i1, ipv6IfIcmpOutAdminProhibs);
1233 	MDIFF(d, i2, i1, ipv6IfIcmpOutTimeExcds);
1234 	MDIFF(d, i2, i1, ipv6IfIcmpOutParmProblems);
1235 	MDIFF(d, i2, i1, ipv6IfIcmpOutPktTooBigs);
1236 	MDIFF(d, i2, i1, ipv6IfIcmpOutEchos);
1237 	MDIFF(d, i2, i1, ipv6IfIcmpOutEchoReplies);
1238 	MDIFF(d, i2, i1, ipv6IfIcmpOutRouterSolicits);
1239 	MDIFF(d, i2, i1, ipv6IfIcmpOutRouterAdvertisements);
1240 	MDIFF(d, i2, i1, ipv6IfIcmpOutNeighborSolicits);
1241 	MDIFF(d, i2, i1, ipv6IfIcmpOutNeighborAdvertisements);
1242 	MDIFF(d, i2, i1, ipv6IfIcmpOutRedirects);
1243 	MDIFF(d, i2, i1, ipv6IfIcmpOutGroupMembQueries);
1244 	MDIFF(d, i2, i1, ipv6IfIcmpOutGroupMembResponses);
1245 	MDIFF(d, i2, i1, ipv6IfIcmpOutGroupMembReductions);
1246 	prevp = diffptr++;
1247 	break;
1248 			}
1249 			case MIB2_TCP: {
1250 				mib2_tcp_t *t2;
1251 				mib2_tcp_t *t1;
1252 				mib2_tcp_t *d;
1253 
1254 				t2 = (mib2_tcp_t *)tempp2->valp;
1255 				t1 = (mib2_tcp_t *)tempp1->valp;
1256 				diffptr->group = tempp2->group;
1257 				diffptr->mib_id = tempp2->mib_id;
1258 				diffptr->length = tempp2->length;
1259 				d = (mib2_tcp_t *)calloc(tempp2->length, 1);
1260 				if (d == NULL)
1261 					goto mibdiff_out_of_memory;
1262 				diffptr->valp = d;
1263 				d->tcpRtoMin = t2->tcpRtoMin;
1264 				d->tcpRtoMax = t2->tcpRtoMax;
1265 				d->tcpMaxConn = t2->tcpMaxConn;
1266 				MDIFF(d, t2, t1, tcpActiveOpens);
1267 				MDIFF(d, t2, t1, tcpPassiveOpens);
1268 				MDIFF(d, t2, t1, tcpAttemptFails);
1269 				MDIFF(d, t2, t1, tcpEstabResets);
1270 				d->tcpCurrEstab = t2->tcpCurrEstab;
1271 				MDIFF(d, t2, t1, tcpHCOutSegs);
1272 				MDIFF(d, t2, t1, tcpOutDataSegs);
1273 				MDIFF(d, t2, t1, tcpOutDataBytes);
1274 				MDIFF(d, t2, t1, tcpRetransSegs);
1275 				MDIFF(d, t2, t1, tcpRetransBytes);
1276 				MDIFF(d, t2, t1, tcpOutAck);
1277 				MDIFF(d, t2, t1, tcpOutAckDelayed);
1278 				MDIFF(d, t2, t1, tcpOutUrg);
1279 				MDIFF(d, t2, t1, tcpOutWinUpdate);
1280 				MDIFF(d, t2, t1, tcpOutWinProbe);
1281 				MDIFF(d, t2, t1, tcpOutControl);
1282 				MDIFF(d, t2, t1, tcpOutRsts);
1283 				MDIFF(d, t2, t1, tcpOutFastRetrans);
1284 				MDIFF(d, t2, t1, tcpHCInSegs);
1285 				MDIFF(d, t2, t1, tcpInAckSegs);
1286 				MDIFF(d, t2, t1, tcpInAckBytes);
1287 				MDIFF(d, t2, t1, tcpInDupAck);
1288 				MDIFF(d, t2, t1, tcpInAckUnsent);
1289 				MDIFF(d, t2, t1, tcpInDataInorderSegs);
1290 				MDIFF(d, t2, t1, tcpInDataInorderBytes);
1291 				MDIFF(d, t2, t1, tcpInDataUnorderSegs);
1292 				MDIFF(d, t2, t1, tcpInDataUnorderBytes);
1293 				MDIFF(d, t2, t1, tcpInDataDupSegs);
1294 				MDIFF(d, t2, t1, tcpInDataDupBytes);
1295 				MDIFF(d, t2, t1, tcpInDataPartDupSegs);
1296 				MDIFF(d, t2, t1, tcpInDataPartDupBytes);
1297 				MDIFF(d, t2, t1, tcpInDataPastWinSegs);
1298 				MDIFF(d, t2, t1, tcpInDataPastWinBytes);
1299 				MDIFF(d, t2, t1, tcpInWinProbe);
1300 				MDIFF(d, t2, t1, tcpInWinUpdate);
1301 				MDIFF(d, t2, t1, tcpInClosed);
1302 				MDIFF(d, t2, t1, tcpRttNoUpdate);
1303 				MDIFF(d, t2, t1, tcpRttUpdate);
1304 				MDIFF(d, t2, t1, tcpTimRetrans);
1305 				MDIFF(d, t2, t1, tcpTimRetransDrop);
1306 				MDIFF(d, t2, t1, tcpTimKeepalive);
1307 				MDIFF(d, t2, t1, tcpTimKeepaliveProbe);
1308 				MDIFF(d, t2, t1, tcpTimKeepaliveDrop);
1309 				MDIFF(d, t2, t1, tcpListenDrop);
1310 				MDIFF(d, t2, t1, tcpListenDropQ0);
1311 				MDIFF(d, t2, t1, tcpHalfOpenDrop);
1312 				MDIFF(d, t2, t1, tcpOutSackRetransSegs);
1313 				prevp = diffptr++;
1314 				break;
1315 			}
1316 			case MIB2_UDP: {
1317 				mib2_udp_t *u2;
1318 				mib2_udp_t *u1;
1319 				mib2_udp_t *d;
1320 
1321 				u2 = (mib2_udp_t *)tempp2->valp;
1322 				u1 = (mib2_udp_t *)tempp1->valp;
1323 				diffptr->group = tempp2->group;
1324 				diffptr->mib_id = tempp2->mib_id;
1325 				diffptr->length = tempp2->length;
1326 				d = (mib2_udp_t *)calloc(tempp2->length, 1);
1327 				if (d == NULL)
1328 					goto mibdiff_out_of_memory;
1329 				diffptr->valp = d;
1330 				MDIFF(d, u2, u1, udpHCInDatagrams);
1331 				MDIFF(d, u2, u1, udpInErrors);
1332 				MDIFF(d, u2, u1, udpHCOutDatagrams);
1333 				MDIFF(d, u2, u1, udpOutErrors);
1334 				prevp = diffptr++;
1335 				break;
1336 			}
1337 			case MIB2_SCTP: {
1338 				mib2_sctp_t *s2;
1339 				mib2_sctp_t *s1;
1340 				mib2_sctp_t *d;
1341 
1342 				s2 = (mib2_sctp_t *)tempp2->valp;
1343 				s1 = (mib2_sctp_t *)tempp1->valp;
1344 				diffptr->group = tempp2->group;
1345 				diffptr->mib_id = tempp2->mib_id;
1346 				diffptr->length = tempp2->length;
1347 				d = (mib2_sctp_t *)calloc(tempp2->length, 1);
1348 				if (d == NULL)
1349 					goto mibdiff_out_of_memory;
1350 				diffptr->valp = d;
1351 				d->sctpRtoAlgorithm = s2->sctpRtoAlgorithm;
1352 				d->sctpRtoMin = s2->sctpRtoMin;
1353 				d->sctpRtoMax = s2->sctpRtoMax;
1354 				d->sctpRtoInitial = s2->sctpRtoInitial;
1355 				d->sctpMaxAssocs = s2->sctpMaxAssocs;
1356 				d->sctpValCookieLife = s2->sctpValCookieLife;
1357 				d->sctpMaxInitRetr = s2->sctpMaxInitRetr;
1358 				d->sctpCurrEstab = s2->sctpCurrEstab;
1359 				MDIFF(d, s2, s1, sctpActiveEstab);
1360 				MDIFF(d, s2, s1, sctpPassiveEstab);
1361 				MDIFF(d, s2, s1, sctpAborted);
1362 				MDIFF(d, s2, s1, sctpShutdowns);
1363 				MDIFF(d, s2, s1, sctpOutOfBlue);
1364 				MDIFF(d, s2, s1, sctpChecksumError);
1365 				MDIFF(d, s2, s1, sctpOutCtrlChunks);
1366 				MDIFF(d, s2, s1, sctpOutOrderChunks);
1367 				MDIFF(d, s2, s1, sctpOutUnorderChunks);
1368 				MDIFF(d, s2, s1, sctpRetransChunks);
1369 				MDIFF(d, s2, s1, sctpOutAck);
1370 				MDIFF(d, s2, s1, sctpOutAckDelayed);
1371 				MDIFF(d, s2, s1, sctpOutWinUpdate);
1372 				MDIFF(d, s2, s1, sctpOutFastRetrans);
1373 				MDIFF(d, s2, s1, sctpOutWinProbe);
1374 				MDIFF(d, s2, s1, sctpInCtrlChunks);
1375 				MDIFF(d, s2, s1, sctpInOrderChunks);
1376 				MDIFF(d, s2, s1, sctpInUnorderChunks);
1377 				MDIFF(d, s2, s1, sctpInAck);
1378 				MDIFF(d, s2, s1, sctpInDupAck);
1379 				MDIFF(d, s2, s1, sctpInAckUnsent);
1380 				MDIFF(d, s2, s1, sctpFragUsrMsgs);
1381 				MDIFF(d, s2, s1, sctpReasmUsrMsgs);
1382 				MDIFF(d, s2, s1, sctpOutSCTPPkts);
1383 				MDIFF(d, s2, s1, sctpInSCTPPkts);
1384 				MDIFF(d, s2, s1, sctpInInvalidCookie);
1385 				MDIFF(d, s2, s1, sctpTimRetrans);
1386 				MDIFF(d, s2, s1, sctpTimRetransDrop);
1387 				MDIFF(d, s2, s1, sctpTimHeartBeatProbe);
1388 				MDIFF(d, s2, s1, sctpTimHeartBeatDrop);
1389 				MDIFF(d, s2, s1, sctpListenDrop);
1390 				MDIFF(d, s2, s1, sctpInClosed);
1391 				prevp = diffptr++;
1392 				break;
1393 			}
1394 			case EXPER_RAWIP: {
1395 				mib2_rawip_t *r2;
1396 				mib2_rawip_t *r1;
1397 				mib2_rawip_t *d;
1398 
1399 				r2 = (mib2_rawip_t *)tempp2->valp;
1400 				r1 = (mib2_rawip_t *)tempp1->valp;
1401 				diffptr->group = tempp2->group;
1402 				diffptr->mib_id = tempp2->mib_id;
1403 				diffptr->length = tempp2->length;
1404 				d = (mib2_rawip_t *)calloc(tempp2->length, 1);
1405 				if (d == NULL)
1406 					goto mibdiff_out_of_memory;
1407 				diffptr->valp = d;
1408 				MDIFF(d, r2, r1, rawipInDatagrams);
1409 				MDIFF(d, r2, r1, rawipInErrors);
1410 				MDIFF(d, r2, r1, rawipInCksumErrs);
1411 				MDIFF(d, r2, r1, rawipOutDatagrams);
1412 				MDIFF(d, r2, r1, rawipOutErrors);
1413 				prevp = diffptr++;
1414 				break;
1415 			}
1416 			/*
1417 			 * there are more "group" types but they aren't
1418 			 * required for the -s and -Ms options
1419 			 */
1420 			}
1421 		} /* 'for' loop 2 ends */
1422 		tempp1 = NULL;
1423 	} /* 'for' loop 1 ends */
1424 	tempp2 = NULL;
1425 	diffptr--;
1426 	diffptr->next_item = NULL;
1427 	return (diffp);
1428 
1429 mibdiff_out_of_memory:;
1430 	mib_item_destroy(&diffp);
1431 	return (NULL);
1432 }
1433 
1434 /*
1435  * mib_item_destroy: cleans up a mib_item_t *
1436  * that was created by calling mib_item_dup or
1437  * mib_item_diff
1438  */
1439 static void
1440 mib_item_destroy(mib_item_t **itemp) {
1441 	int	nitems = 0;
1442 	int	c = 0;
1443 	mib_item_t *tempp;
1444 
1445 	if (itemp == NULL || *itemp == NULL)
1446 		return;
1447 
1448 	for (tempp = *itemp; tempp != NULL; tempp = tempp->next_item)
1449 		if (tempp->mib_id == 0)
1450 			nitems++;
1451 		else
1452 			return;	/* cannot destroy! */
1453 
1454 	if (nitems == 0)
1455 		return;		/* cannot destroy! */
1456 
1457 	for (c = nitems - 1; c >= 0; c--) {
1458 		if ((itemp[0][c]).valp != NULL)
1459 			free((itemp[0][c]).valp);
1460 	}
1461 	free(*itemp);
1462 
1463 	*itemp = NULL;
1464 }
1465 
1466 /* Compare two Octet_ts.  Return B_TRUE if they match, B_FALSE if not. */
1467 static boolean_t
1468 octetstrmatch(const Octet_t *a, const Octet_t *b)
1469 {
1470 	if (a == NULL || b == NULL)
1471 		return (B_FALSE);
1472 
1473 	if (a->o_length != b->o_length)
1474 		return (B_FALSE);
1475 
1476 	return (memcmp(a->o_bytes, b->o_bytes, a->o_length) == 0);
1477 }
1478 
1479 /* If octetstr() changes make an appropriate change to STR_EXPAND */
1480 static char *
1481 octetstr(const Octet_t *op, int code, char *dst, uint_t dstlen)
1482 {
1483 	int	i;
1484 	char	*cp;
1485 
1486 	cp = dst;
1487 	if (op) {
1488 		for (i = 0; i < op->o_length; i++) {
1489 			switch (code) {
1490 			case 'd':
1491 				if (cp - dst + 4 > dstlen) {
1492 					*cp = '\0';
1493 					return (dst);
1494 				}
1495 				(void) snprintf(cp, 5, "%d.",
1496 				    0xff & op->o_bytes[i]);
1497 				cp = strchr(cp, '\0');
1498 				break;
1499 			case 'a':
1500 				if (cp - dst + 1 > dstlen) {
1501 					*cp = '\0';
1502 					return (dst);
1503 				}
1504 				*cp++ = op->o_bytes[i];
1505 				break;
1506 			case 'h':
1507 			default:
1508 				if (cp - dst + 3 > dstlen) {
1509 					*cp = '\0';
1510 					return (dst);
1511 				}
1512 				(void) snprintf(cp, 4, "%02x:",
1513 				    0xff & op->o_bytes[i]);
1514 				cp += 3;
1515 				break;
1516 			}
1517 		}
1518 	}
1519 	if (code != 'a' && cp != dst)
1520 		cp--;
1521 	*cp = '\0';
1522 	return (dst);
1523 }
1524 
1525 static const char *
1526 mitcp_state(int state, const mib2_transportMLPEntry_t *attr)
1527 {
1528 	static char tcpsbuf[50];
1529 	const char *cp;
1530 
1531 	switch (state) {
1532 	case TCPS_CLOSED:
1533 		cp = "CLOSED";
1534 		break;
1535 	case TCPS_IDLE:
1536 		cp = "IDLE";
1537 		break;
1538 	case TCPS_BOUND:
1539 		cp = "BOUND";
1540 		break;
1541 	case TCPS_LISTEN:
1542 		cp = "LISTEN";
1543 		break;
1544 	case TCPS_SYN_SENT:
1545 		cp = "SYN_SENT";
1546 		break;
1547 	case TCPS_SYN_RCVD:
1548 		cp = "SYN_RCVD";
1549 		break;
1550 	case TCPS_ESTABLISHED:
1551 		cp = "ESTABLISHED";
1552 		break;
1553 	case TCPS_CLOSE_WAIT:
1554 		cp = "CLOSE_WAIT";
1555 		break;
1556 	case TCPS_FIN_WAIT_1:
1557 		cp = "FIN_WAIT_1";
1558 		break;
1559 	case TCPS_CLOSING:
1560 		cp = "CLOSING";
1561 		break;
1562 	case TCPS_LAST_ACK:
1563 		cp = "LAST_ACK";
1564 		break;
1565 	case TCPS_FIN_WAIT_2:
1566 		cp = "FIN_WAIT_2";
1567 		break;
1568 	case TCPS_TIME_WAIT:
1569 		cp = "TIME_WAIT";
1570 		break;
1571 	default:
1572 		(void) snprintf(tcpsbuf, sizeof (tcpsbuf),
1573 		    "UnknownState(%d)", state);
1574 		cp = tcpsbuf;
1575 		break;
1576 	}
1577 
1578 	if (RSECflag && attr != NULL && attr->tme_flags != 0) {
1579 		if (cp != tcpsbuf) {
1580 			(void) strlcpy(tcpsbuf, cp, sizeof (tcpsbuf));
1581 			cp = tcpsbuf;
1582 		}
1583 		if (attr->tme_flags & MIB2_TMEF_PRIVATE)
1584 			(void) strlcat(tcpsbuf, " P", sizeof (tcpsbuf));
1585 		if (attr->tme_flags & MIB2_TMEF_SHARED)
1586 			(void) strlcat(tcpsbuf, " S", sizeof (tcpsbuf));
1587 	}
1588 
1589 	return (cp);
1590 }
1591 
1592 static const char *
1593 miudp_state(int state, const mib2_transportMLPEntry_t *attr)
1594 {
1595 	static char udpsbuf[50];
1596 	const char *cp;
1597 
1598 	switch (state) {
1599 	case MIB2_UDP_unbound:
1600 		cp = "Unbound";
1601 		break;
1602 	case MIB2_UDP_idle:
1603 		cp = "Idle";
1604 		break;
1605 	case MIB2_UDP_connected:
1606 		cp = "Connected";
1607 		break;
1608 	default:
1609 		(void) snprintf(udpsbuf, sizeof (udpsbuf),
1610 		    "Unknown State(%d)", state);
1611 		cp = udpsbuf;
1612 		break;
1613 	}
1614 
1615 	if (RSECflag && attr != NULL && attr->tme_flags != 0) {
1616 		if (cp != udpsbuf) {
1617 			(void) strlcpy(udpsbuf, cp, sizeof (udpsbuf));
1618 			cp = udpsbuf;
1619 		}
1620 		if (attr->tme_flags & MIB2_TMEF_PRIVATE)
1621 			(void) strlcat(udpsbuf, " P", sizeof (udpsbuf));
1622 		if (attr->tme_flags & MIB2_TMEF_SHARED)
1623 			(void) strlcat(udpsbuf, " S", sizeof (udpsbuf));
1624 	}
1625 
1626 	return (cp);
1627 }
1628 
1629 static int odd;
1630 
1631 static void
1632 prval_init(void)
1633 {
1634 	odd = 0;
1635 }
1636 
1637 static void
1638 prval(char *str, Counter val)
1639 {
1640 	(void) printf("\t%-20s=%6u", str, val);
1641 	if (odd++ & 1)
1642 		(void) putchar('\n');
1643 }
1644 
1645 static void
1646 prval64(char *str, Counter64 val)
1647 {
1648 	(void) printf("\t%-20s=%6llu", str, val);
1649 	if (odd++ & 1)
1650 		(void) putchar('\n');
1651 }
1652 
1653 static void
1654 pr_int_val(char *str, int val)
1655 {
1656 	(void) printf("\t%-20s=%6d", str, val);
1657 	if (odd++ & 1)
1658 		(void) putchar('\n');
1659 }
1660 
1661 static void
1662 pr_sctp_rtoalgo(char *str, int val)
1663 {
1664 	(void) printf("\t%-20s=", str);
1665 	switch (val) {
1666 		case MIB2_SCTP_RTOALGO_OTHER:
1667 			(void) printf("%6.6s", "other");
1668 			break;
1669 
1670 		case MIB2_SCTP_RTOALGO_VANJ:
1671 			(void) printf("%6.6s", "vanj");
1672 			break;
1673 
1674 		default:
1675 			(void) printf("%6d", val);
1676 			break;
1677 	}
1678 	if (odd++ & 1)
1679 		(void) putchar('\n');
1680 }
1681 
1682 static void
1683 prval_end(void)
1684 {
1685 	if (odd++ & 1)
1686 		(void) putchar('\n');
1687 }
1688 
1689 /* Extract constant sizes */
1690 static void
1691 mib_get_constants(mib_item_t *item)
1692 {
1693 	/* 'for' loop 1: */
1694 	for (; item; item = item->next_item) {
1695 		if (item->mib_id != 0)
1696 			continue; /* 'for' loop 1 */
1697 
1698 		switch (item->group) {
1699 		case MIB2_IP: {
1700 			mib2_ip_t	*ip = (mib2_ip_t *)item->valp;
1701 
1702 			ipAddrEntrySize = ip->ipAddrEntrySize;
1703 			ipRouteEntrySize = ip->ipRouteEntrySize;
1704 			ipNetToMediaEntrySize = ip->ipNetToMediaEntrySize;
1705 			ipMemberEntrySize = ip->ipMemberEntrySize;
1706 			ipGroupSourceEntrySize = ip->ipGroupSourceEntrySize;
1707 			ipRouteAttributeSize = ip->ipRouteAttributeSize;
1708 			transportMLPSize = ip->transportMLPSize;
1709 			assert(IS_P2ALIGNED(ipAddrEntrySize,
1710 			    sizeof (mib2_ipAddrEntry_t *)) &&
1711 			    IS_P2ALIGNED(ipRouteEntrySize,
1712 				sizeof (mib2_ipRouteEntry_t *)) &&
1713 			    IS_P2ALIGNED(ipNetToMediaEntrySize,
1714 				sizeof (mib2_ipNetToMediaEntry_t *)) &&
1715 			    IS_P2ALIGNED(ipMemberEntrySize,
1716 				sizeof (ip_member_t *)) &&
1717 			    IS_P2ALIGNED(ipGroupSourceEntrySize,
1718 				sizeof (ip_grpsrc_t *)) &&
1719 			    IS_P2ALIGNED(ipRouteAttributeSize,
1720 				sizeof (mib2_ipAttributeEntry_t *)) &&
1721 			    IS_P2ALIGNED(transportMLPSize,
1722 				sizeof (mib2_transportMLPEntry_t *)));
1723 			break;
1724 		}
1725 		case EXPER_DVMRP: {
1726 			struct mrtstat	*mrts = (struct mrtstat *)item->valp;
1727 
1728 			vifctlSize = mrts->mrts_vifctlSize;
1729 			mfcctlSize = mrts->mrts_mfcctlSize;
1730 			assert(IS_P2ALIGNED(vifctlSize,
1731 			    sizeof (struct vifclt *)) &&
1732 			    IS_P2ALIGNED(mfcctlSize, sizeof (struct mfcctl *)));
1733 			break;
1734 		}
1735 		case MIB2_IP6: {
1736 			mib2_ipv6IfStatsEntry_t *ip6;
1737 			/* Just use the first entry */
1738 
1739 			ip6 = (mib2_ipv6IfStatsEntry_t *)item->valp;
1740 			ipv6IfStatsEntrySize = ip6->ipv6IfStatsEntrySize;
1741 			ipv6AddrEntrySize = ip6->ipv6AddrEntrySize;
1742 			ipv6RouteEntrySize = ip6->ipv6RouteEntrySize;
1743 			ipv6NetToMediaEntrySize = ip6->ipv6NetToMediaEntrySize;
1744 			ipv6MemberEntrySize = ip6->ipv6MemberEntrySize;
1745 			ipv6GroupSourceEntrySize =
1746 			    ip6->ipv6GroupSourceEntrySize;
1747 			assert(IS_P2ALIGNED(ipv6IfStatsEntrySize,
1748 			    sizeof (mib2_ipv6IfStatsEntry_t *)) &&
1749 			    IS_P2ALIGNED(ipv6AddrEntrySize,
1750 				sizeof (mib2_ipv6AddrEntry_t *)) &&
1751 			    IS_P2ALIGNED(ipv6RouteEntrySize,
1752 				sizeof (mib2_ipv6RouteEntry_t *)) &&
1753 			    IS_P2ALIGNED(ipv6NetToMediaEntrySize,
1754 				sizeof (mib2_ipv6NetToMediaEntry_t *)) &&
1755 			    IS_P2ALIGNED(ipv6MemberEntrySize,
1756 				sizeof (ipv6_member_t *)) &&
1757 			    IS_P2ALIGNED(ipv6GroupSourceEntrySize,
1758 				sizeof (ipv6_grpsrc_t *)));
1759 			break;
1760 		}
1761 		case MIB2_ICMP6: {
1762 			mib2_ipv6IfIcmpEntry_t *icmp6;
1763 			/* Just use the first entry */
1764 
1765 			icmp6 = (mib2_ipv6IfIcmpEntry_t *)item->valp;
1766 			ipv6IfIcmpEntrySize = icmp6->ipv6IfIcmpEntrySize;
1767 			assert(IS_P2ALIGNED(ipv6IfIcmpEntrySize,
1768 			    sizeof (mib2_ipv6IfIcmpEntry_t *)));
1769 			break;
1770 		}
1771 		case MIB2_TCP: {
1772 			mib2_tcp_t	*tcp = (mib2_tcp_t *)item->valp;
1773 
1774 			tcpConnEntrySize = tcp->tcpConnTableSize;
1775 			tcp6ConnEntrySize = tcp->tcp6ConnTableSize;
1776 			assert(IS_P2ALIGNED(tcpConnEntrySize,
1777 			    sizeof (mib2_tcpConnEntry_t *)) &&
1778 			    IS_P2ALIGNED(tcp6ConnEntrySize,
1779 				sizeof (mib2_tcp6ConnEntry_t *)));
1780 			break;
1781 		}
1782 		case MIB2_UDP: {
1783 			mib2_udp_t	*udp = (mib2_udp_t *)item->valp;
1784 
1785 			udpEntrySize = udp->udpEntrySize;
1786 			udp6EntrySize = udp->udp6EntrySize;
1787 			assert(IS_P2ALIGNED(udpEntrySize,
1788 			    sizeof (mib2_udpEntry_t *)) &&
1789 			    IS_P2ALIGNED(udp6EntrySize,
1790 				sizeof (mib2_udp6Entry_t *)));
1791 			break;
1792 		}
1793 		case MIB2_SCTP: {
1794 			mib2_sctp_t	*sctp = (mib2_sctp_t *)item->valp;
1795 
1796 			sctpEntrySize = sctp->sctpEntrySize;
1797 			sctpLocalEntrySize = sctp->sctpLocalEntrySize;
1798 			sctpRemoteEntrySize = sctp->sctpRemoteEntrySize;
1799 			break;
1800 		}
1801 		}
1802 	} /* 'for' loop 1 ends */
1803 
1804 	if (Dflag) {
1805 		(void) puts("mib_get_constants:");
1806 		(void) printf("\tipv6IfStatsEntrySize %d\n",
1807 		    ipv6IfStatsEntrySize);
1808 		(void) printf("\tipAddrEntrySize %d\n", ipAddrEntrySize);
1809 		(void) printf("\tipRouteEntrySize %d\n", ipRouteEntrySize);
1810 		(void) printf("\tipNetToMediaEntrySize %d\n",
1811 		    ipNetToMediaEntrySize);
1812 		(void) printf("\tipMemberEntrySize %d\n", ipMemberEntrySize);
1813 		(void) printf("\tipRouteAttributeSize %d\n",
1814 		    ipRouteAttributeSize);
1815 		(void) printf("\tvifctlSize %d\n", vifctlSize);
1816 		(void) printf("\tmfcctlSize %d\n", mfcctlSize);
1817 
1818 		(void) printf("\tipv6AddrEntrySize %d\n", ipv6AddrEntrySize);
1819 		(void) printf("\tipv6RouteEntrySize %d\n", ipv6RouteEntrySize);
1820 		(void) printf("\tipv6NetToMediaEntrySize %d\n",
1821 		    ipv6NetToMediaEntrySize);
1822 		(void) printf("\tipv6MemberEntrySize %d\n",
1823 		    ipv6MemberEntrySize);
1824 		(void) printf("\tipv6IfIcmpEntrySize %d\n",
1825 		    ipv6IfIcmpEntrySize);
1826 		(void) printf("\ttransportMLPSize %d\n", transportMLPSize);
1827 		(void) printf("\ttcpConnEntrySize %d\n", tcpConnEntrySize);
1828 		(void) printf("\ttcp6ConnEntrySize %d\n", tcp6ConnEntrySize);
1829 		(void) printf("\tudpEntrySize %d\n", udpEntrySize);
1830 		(void) printf("\tudp6EntrySize %d\n", udp6EntrySize);
1831 		(void) printf("\tsctpEntrySize %d\n", sctpEntrySize);
1832 		(void) printf("\tsctpLocalEntrySize %d\n", sctpLocalEntrySize);
1833 		(void) printf("\tsctpRemoteEntrySize %d\n",
1834 		    sctpRemoteEntrySize);
1835 	}
1836 }
1837 
1838 
1839 /* ----------------------------- STAT_REPORT ------------------------------- */
1840 
1841 static void
1842 stat_report(mib_item_t *item)
1843 {
1844 	int	jtemp = 0;
1845 	char	ifname[LIFNAMSIZ + 1];
1846 	char	*ifnamep;
1847 
1848 	/* 'for' loop 1: */
1849 	for (; item; item = item->next_item) {
1850 		if (Dflag) {
1851 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
1852 			(void) printf("Group = %d, mib_id = %d, "
1853 			    "length = %d, valp = 0x%p\n",
1854 			    item->group, item->mib_id,
1855 			    item->length, item->valp);
1856 		}
1857 		if (item->mib_id != 0)
1858 			continue; /* 'for' loop 1 */
1859 
1860 		switch (item->group) {
1861 		case MIB2_IP: {
1862 			mib2_ip_t	*ip = (mib2_ip_t *)item->valp;
1863 
1864 			if (protocol_selected(IPPROTO_IP) &&
1865 			    family_selected(AF_INET)) {
1866 				(void) fputs(v4compat ? "\nIP" : "\nIPv4",
1867 				    stdout);
1868 				print_ip_stats(ip);
1869 			}
1870 			break;
1871 		}
1872 		case MIB2_ICMP: {
1873 			mib2_icmp_t	*icmp =
1874 			    (mib2_icmp_t *)item->valp;
1875 
1876 			if (protocol_selected(IPPROTO_ICMP) &&
1877 			    family_selected(AF_INET)) {
1878 				(void) fputs(v4compat ? "\nICMP" : "\nICMPv4",
1879 				    stdout);
1880 				print_icmp_stats(icmp);
1881 			}
1882 			break;
1883 		}
1884 		case MIB2_IP6: {
1885 			mib2_ipv6IfStatsEntry_t *ip6;
1886 			mib2_ipv6IfStatsEntry_t sum6;
1887 
1888 			if (!(protocol_selected(IPPROTO_IPV6)) ||
1889 			    !(family_selected(AF_INET6)))
1890 				break;
1891 			bzero(&sum6, sizeof (sum6));
1892 			/* 'for' loop 2a: */
1893 			for (ip6 = (mib2_ipv6IfStatsEntry_t *)item->valp;
1894 			    (char *)ip6 < (char *)item->valp
1895 			    + item->length;
1896 			    /* LINTED: (note 1) */
1897 			    ip6 = (mib2_ipv6IfStatsEntry_t *)((char *)ip6 +
1898 			    ipv6IfStatsEntrySize)) {
1899 
1900 				if (ip6->ipv6IfIndex == 0) {
1901 					/*
1902 					 * The "unknown interface" ip6
1903 					 * mib. Just add to the sum.
1904 					 */
1905 					sum_ip6_stats(ip6, &sum6);
1906 					continue; /* 'for' loop 2a */
1907 				}
1908 				ifnamep = if_indextoname(
1909 				    ip6->ipv6IfIndex,
1910 				    ifname);
1911 				if (ifnamep == NULL) {
1912 					(void) printf(
1913 					    "Invalid ifindex %d\n",
1914 					    ip6->ipv6IfIndex);
1915 					continue; /* 'for' loop 2a */
1916 				}
1917 
1918 				if (Aflag) {
1919 					(void) printf("\nIPv6 for %s\n",
1920 					    ifnamep);
1921 					print_ip6_stats(ip6);
1922 				}
1923 				sum_ip6_stats(ip6, &sum6);
1924 			} /* 'for' loop 2a ends */
1925 			(void) fputs("\nIPv6", stdout);
1926 			print_ip6_stats(&sum6);
1927 			break;
1928 		}
1929 		case MIB2_ICMP6: {
1930 			mib2_ipv6IfIcmpEntry_t *icmp6;
1931 			mib2_ipv6IfIcmpEntry_t sum6;
1932 
1933 			if (!(protocol_selected(IPPROTO_ICMPV6)) ||
1934 			    !(family_selected(AF_INET6)))
1935 				break;
1936 			bzero(&sum6, sizeof (sum6));
1937 			/* 'for' loop 2b: */
1938 			for (icmp6 =
1939 			    (mib2_ipv6IfIcmpEntry_t *)item->valp;
1940 			    (char *)icmp6 < (char *)item->valp
1941 				+ item->length;
1942 			    icmp6 =
1943 				/* LINTED: (note 1) */
1944 				(mib2_ipv6IfIcmpEntry_t *)((char *)icmp6
1945 			    + ipv6IfIcmpEntrySize)) {
1946 
1947 				if (icmp6->ipv6IfIcmpIfIndex == 0) {
1948 					/*
1949 					 * The "unknown interface" icmp6
1950 					 * mib. Just add to the sum.
1951 					 */
1952 					sum_icmp6_stats(icmp6, &sum6);
1953 					continue; /* 'for' loop 2b: */
1954 				}
1955 				ifnamep = if_indextoname(
1956 				    icmp6->ipv6IfIcmpIfIndex, ifname);
1957 				if (ifnamep == NULL) {
1958 					(void) printf(
1959 					    "Invalid ifindex %d\n",
1960 					    icmp6->ipv6IfIcmpIfIndex);
1961 					continue; /* 'for' loop 2b: */
1962 				}
1963 
1964 				if (Aflag) {
1965 					(void) printf(
1966 					    "\nICMPv6 for %s\n",
1967 					    ifnamep);
1968 					print_icmp6_stats(icmp6);
1969 				}
1970 				sum_icmp6_stats(icmp6, &sum6);
1971 			} /* 'for' loop 2b ends */
1972 			(void) fputs("\nICMPv6", stdout);
1973 			print_icmp6_stats(&sum6);
1974 			break;
1975 		}
1976 		case MIB2_TCP: {
1977 			mib2_tcp_t	*tcp = (mib2_tcp_t *)item->valp;
1978 
1979 			if (protocol_selected(IPPROTO_TCP) &&
1980 			    (family_selected(AF_INET) ||
1981 			    family_selected(AF_INET6))) {
1982 				(void) fputs("\nTCP", stdout);
1983 				print_tcp_stats(tcp);
1984 			}
1985 			break;
1986 		}
1987 		case MIB2_UDP: {
1988 			mib2_udp_t	*udp = (mib2_udp_t *)item->valp;
1989 
1990 			if (protocol_selected(IPPROTO_UDP) &&
1991 			    (family_selected(AF_INET) ||
1992 			    family_selected(AF_INET6))) {
1993 				(void) fputs("\nUDP", stdout);
1994 				print_udp_stats(udp);
1995 			}
1996 			break;
1997 		}
1998 		case MIB2_SCTP: {
1999 			mib2_sctp_t	*sctp = (mib2_sctp_t *)item->valp;
2000 
2001 			if (protocol_selected(IPPROTO_SCTP) &&
2002 			    (family_selected(AF_INET) ||
2003 			    family_selected(AF_INET6))) {
2004 				(void) fputs("\nSCTP", stdout);
2005 				print_sctp_stats(sctp);
2006 			}
2007 			break;
2008 		}
2009 		case EXPER_RAWIP: {
2010 			mib2_rawip_t	*rawip =
2011 			    (mib2_rawip_t *)item->valp;
2012 
2013 			if (protocol_selected(IPPROTO_RAW) &&
2014 			    (family_selected(AF_INET) ||
2015 			    family_selected(AF_INET6))) {
2016 				(void) fputs("\nRAWIP", stdout);
2017 				print_rawip_stats(rawip);
2018 			}
2019 			break;
2020 		}
2021 		case EXPER_IGMP: {
2022 			struct igmpstat	*igps =
2023 			    (struct igmpstat *)item->valp;
2024 
2025 			if (protocol_selected(IPPROTO_IGMP) &&
2026 			    (family_selected(AF_INET))) {
2027 				(void) fputs("\nIGMP:\n", stdout);
2028 				print_igmp_stats(igps);
2029 			}
2030 			break;
2031 		}
2032 		}
2033 	} /* 'for' loop 1 ends */
2034 	(void) putchar('\n');
2035 	(void) fflush(stdout);
2036 }
2037 
2038 static void
2039 print_ip_stats(mib2_ip_t *ip)
2040 {
2041 	prval_init();
2042 	pr_int_val("ipForwarding",	ip->ipForwarding);
2043 	pr_int_val("ipDefaultTTL",	ip->ipDefaultTTL);
2044 	prval("ipInReceives",		ip->ipInReceives);
2045 	prval("ipInHdrErrors",		ip->ipInHdrErrors);
2046 	prval("ipInAddrErrors",		ip->ipInAddrErrors);
2047 	prval("ipInCksumErrs",		ip->ipInCksumErrs);
2048 	prval("ipForwDatagrams",	ip->ipForwDatagrams);
2049 	prval("ipForwProhibits",	ip->ipForwProhibits);
2050 	prval("ipInUnknownProtos",	ip->ipInUnknownProtos);
2051 	prval("ipInDiscards",		ip->ipInDiscards);
2052 	prval("ipInDelivers",		ip->ipInDelivers);
2053 	prval("ipOutRequests",		ip->ipOutRequests);
2054 	prval("ipOutDiscards",		ip->ipOutDiscards);
2055 	prval("ipOutNoRoutes",		ip->ipOutNoRoutes);
2056 	pr_int_val("ipReasmTimeout",	ip->ipReasmTimeout);
2057 	prval("ipReasmReqds",		ip->ipReasmReqds);
2058 	prval("ipReasmOKs",		ip->ipReasmOKs);
2059 	prval("ipReasmFails",		ip->ipReasmFails);
2060 	prval("ipReasmDuplicates",	ip->ipReasmDuplicates);
2061 	prval("ipReasmPartDups",	ip->ipReasmPartDups);
2062 	prval("ipFragOKs",		ip->ipFragOKs);
2063 	prval("ipFragFails",		ip->ipFragFails);
2064 	prval("ipFragCreates",		ip->ipFragCreates);
2065 	prval("ipRoutingDiscards",	ip->ipRoutingDiscards);
2066 
2067 	prval("tcpInErrs",		ip->tcpInErrs);
2068 	prval("udpNoPorts",		ip->udpNoPorts);
2069 	prval("udpInCksumErrs",		ip->udpInCksumErrs);
2070 	prval("udpInOverflows",		ip->udpInOverflows);
2071 	prval("rawipInOverflows",	ip->rawipInOverflows);
2072 	prval("ipsecInSucceeded",	ip->ipsecInSucceeded);
2073 	prval("ipsecInFailed",		ip->ipsecInFailed);
2074 	prval("ipInIPv6",		ip->ipInIPv6);
2075 	prval("ipOutIPv6",		ip->ipOutIPv6);
2076 	prval("ipOutSwitchIPv6",	ip->ipOutSwitchIPv6);
2077 	prval_end();
2078 }
2079 
2080 static void
2081 print_icmp_stats(mib2_icmp_t *icmp)
2082 {
2083 	prval_init();
2084 	prval("icmpInMsgs",		icmp->icmpInMsgs);
2085 	prval("icmpInErrors",		icmp->icmpInErrors);
2086 	prval("icmpInCksumErrs",	icmp->icmpInCksumErrs);
2087 	prval("icmpInUnknowns",		icmp->icmpInUnknowns);
2088 	prval("icmpInDestUnreachs",	icmp->icmpInDestUnreachs);
2089 	prval("icmpInTimeExcds",	icmp->icmpInTimeExcds);
2090 	prval("icmpInParmProbs",	icmp->icmpInParmProbs);
2091 	prval("icmpInSrcQuenchs",	icmp->icmpInSrcQuenchs);
2092 	prval("icmpInRedirects",	icmp->icmpInRedirects);
2093 	prval("icmpInBadRedirects",	icmp->icmpInBadRedirects);
2094 	prval("icmpInEchos",		icmp->icmpInEchos);
2095 	prval("icmpInEchoReps",		icmp->icmpInEchoReps);
2096 	prval("icmpInTimestamps",	icmp->icmpInTimestamps);
2097 	prval("icmpInTimestampReps",	icmp->icmpInTimestampReps);
2098 	prval("icmpInAddrMasks",	icmp->icmpInAddrMasks);
2099 	prval("icmpInAddrMaskReps",	icmp->icmpInAddrMaskReps);
2100 	prval("icmpInFragNeeded",	icmp->icmpInFragNeeded);
2101 	prval("icmpOutMsgs",		icmp->icmpOutMsgs);
2102 	prval("icmpOutDrops",		icmp->icmpOutDrops);
2103 	prval("icmpOutErrors",		icmp->icmpOutErrors);
2104 	prval("icmpOutDestUnreachs",	icmp->icmpOutDestUnreachs);
2105 	prval("icmpOutTimeExcds",	icmp->icmpOutTimeExcds);
2106 	prval("icmpOutParmProbs",	icmp->icmpOutParmProbs);
2107 	prval("icmpOutSrcQuenchs",	icmp->icmpOutSrcQuenchs);
2108 	prval("icmpOutRedirects",	icmp->icmpOutRedirects);
2109 	prval("icmpOutEchos",		icmp->icmpOutEchos);
2110 	prval("icmpOutEchoReps",	icmp->icmpOutEchoReps);
2111 	prval("icmpOutTimestamps",	icmp->icmpOutTimestamps);
2112 	prval("icmpOutTimestampReps",	icmp->icmpOutTimestampReps);
2113 	prval("icmpOutAddrMasks",	icmp->icmpOutAddrMasks);
2114 	prval("icmpOutAddrMaskReps",	icmp->icmpOutAddrMaskReps);
2115 	prval("icmpOutFragNeeded",	icmp->icmpOutFragNeeded);
2116 	prval("icmpInOverflows",	icmp->icmpInOverflows);
2117 	prval_end();
2118 }
2119 
2120 static void
2121 print_ip6_stats(mib2_ipv6IfStatsEntry_t *ip6)
2122 {
2123 	prval_init();
2124 	prval("ipv6Forwarding",		ip6->ipv6Forwarding);
2125 	prval("ipv6DefaultHopLimit",	ip6->ipv6DefaultHopLimit);
2126 
2127 	prval("ipv6InReceives",		ip6->ipv6InReceives);
2128 	prval("ipv6InHdrErrors",	ip6->ipv6InHdrErrors);
2129 	prval("ipv6InTooBigErrors",	ip6->ipv6InTooBigErrors);
2130 	prval("ipv6InNoRoutes",		ip6->ipv6InNoRoutes);
2131 	prval("ipv6InAddrErrors",	ip6->ipv6InAddrErrors);
2132 	prval("ipv6InUnknownProtos",	ip6->ipv6InUnknownProtos);
2133 	prval("ipv6InTruncatedPkts",	ip6->ipv6InTruncatedPkts);
2134 	prval("ipv6InDiscards",		ip6->ipv6InDiscards);
2135 	prval("ipv6InDelivers",		ip6->ipv6InDelivers);
2136 	prval("ipv6OutForwDatagrams",	ip6->ipv6OutForwDatagrams);
2137 	prval("ipv6OutRequests",	ip6->ipv6OutRequests);
2138 	prval("ipv6OutDiscards",	ip6->ipv6OutDiscards);
2139 	prval("ipv6OutNoRoutes",	ip6->ipv6OutNoRoutes);
2140 	prval("ipv6OutFragOKs",		ip6->ipv6OutFragOKs);
2141 	prval("ipv6OutFragFails",	ip6->ipv6OutFragFails);
2142 	prval("ipv6OutFragCreates",	ip6->ipv6OutFragCreates);
2143 	prval("ipv6ReasmReqds",		ip6->ipv6ReasmReqds);
2144 	prval("ipv6ReasmOKs",		ip6->ipv6ReasmOKs);
2145 	prval("ipv6ReasmFails",		ip6->ipv6ReasmFails);
2146 	prval("ipv6InMcastPkts",	ip6->ipv6InMcastPkts);
2147 	prval("ipv6OutMcastPkts",	ip6->ipv6OutMcastPkts);
2148 	prval("ipv6ReasmDuplicates",	ip6->ipv6ReasmDuplicates);
2149 	prval("ipv6ReasmPartDups",	ip6->ipv6ReasmPartDups);
2150 	prval("ipv6ForwProhibits",	ip6->ipv6ForwProhibits);
2151 	prval("udpInCksumErrs",		ip6->udpInCksumErrs);
2152 	prval("udpInOverflows",		ip6->udpInOverflows);
2153 	prval("rawipInOverflows",	ip6->rawipInOverflows);
2154 	prval("ipv6InIPv4",		ip6->ipv6InIPv4);
2155 	prval("ipv6OutIPv4",		ip6->ipv6OutIPv4);
2156 	prval("ipv6OutSwitchIPv4",	ip6->ipv6OutSwitchIPv4);
2157 	prval_end();
2158 }
2159 
2160 static void
2161 print_icmp6_stats(mib2_ipv6IfIcmpEntry_t *icmp6)
2162 {
2163 	prval_init();
2164 	prval("icmp6InMsgs",		icmp6->ipv6IfIcmpInMsgs);
2165 	prval("icmp6InErrors",		icmp6->ipv6IfIcmpInErrors);
2166 	prval("icmp6InDestUnreachs",	icmp6->ipv6IfIcmpInDestUnreachs);
2167 	prval("icmp6InAdminProhibs",	icmp6->ipv6IfIcmpInAdminProhibs);
2168 	prval("icmp6InTimeExcds",	icmp6->ipv6IfIcmpInTimeExcds);
2169 	prval("icmp6InParmProblems",	icmp6->ipv6IfIcmpInParmProblems);
2170 	prval("icmp6InPktTooBigs",	icmp6->ipv6IfIcmpInPktTooBigs);
2171 	prval("icmp6InEchos",		icmp6->ipv6IfIcmpInEchos);
2172 	prval("icmp6InEchoReplies",	icmp6->ipv6IfIcmpInEchoReplies);
2173 	prval("icmp6InRouterSols",	icmp6->ipv6IfIcmpInRouterSolicits);
2174 	prval("icmp6InRouterAds",
2175 	    icmp6->ipv6IfIcmpInRouterAdvertisements);
2176 	prval("icmp6InNeighborSols",	icmp6->ipv6IfIcmpInNeighborSolicits);
2177 	prval("icmp6InNeighborAds",
2178 	    icmp6->ipv6IfIcmpInNeighborAdvertisements);
2179 	prval("icmp6InRedirects",	icmp6->ipv6IfIcmpInRedirects);
2180 	prval("icmp6InBadRedirects",	icmp6->ipv6IfIcmpInBadRedirects);
2181 	prval("icmp6InGroupQueries",	icmp6->ipv6IfIcmpInGroupMembQueries);
2182 	prval("icmp6InGroupResps",	icmp6->ipv6IfIcmpInGroupMembResponses);
2183 	prval("icmp6InGroupReds",	icmp6->ipv6IfIcmpInGroupMembReductions);
2184 	prval("icmp6InOverflows",	icmp6->ipv6IfIcmpInOverflows);
2185 	prval_end();
2186 	prval_init();
2187 	prval("icmp6OutMsgs",		icmp6->ipv6IfIcmpOutMsgs);
2188 	prval("icmp6OutErrors",		icmp6->ipv6IfIcmpOutErrors);
2189 	prval("icmp6OutDestUnreachs",	icmp6->ipv6IfIcmpOutDestUnreachs);
2190 	prval("icmp6OutAdminProhibs",	icmp6->ipv6IfIcmpOutAdminProhibs);
2191 	prval("icmp6OutTimeExcds",	icmp6->ipv6IfIcmpOutTimeExcds);
2192 	prval("icmp6OutParmProblems",	icmp6->ipv6IfIcmpOutParmProblems);
2193 	prval("icmp6OutPktTooBigs",	icmp6->ipv6IfIcmpOutPktTooBigs);
2194 	prval("icmp6OutEchos",		icmp6->ipv6IfIcmpOutEchos);
2195 	prval("icmp6OutEchoReplies",	icmp6->ipv6IfIcmpOutEchoReplies);
2196 	prval("icmp6OutRouterSols",	icmp6->ipv6IfIcmpOutRouterSolicits);
2197 	prval("icmp6OutRouterAds",
2198 	    icmp6->ipv6IfIcmpOutRouterAdvertisements);
2199 	prval("icmp6OutNeighborSols",	icmp6->ipv6IfIcmpOutNeighborSolicits);
2200 	prval("icmp6OutNeighborAds",
2201 	    icmp6->ipv6IfIcmpOutNeighborAdvertisements);
2202 	prval("icmp6OutRedirects",	icmp6->ipv6IfIcmpOutRedirects);
2203 	prval("icmp6OutGroupQueries",	icmp6->ipv6IfIcmpOutGroupMembQueries);
2204 	prval("icmp6OutGroupResps",
2205 	    icmp6->ipv6IfIcmpOutGroupMembResponses);
2206 	prval("icmp6OutGroupReds",
2207 	    icmp6->ipv6IfIcmpOutGroupMembReductions);
2208 	prval_end();
2209 }
2210 
2211 static void
2212 print_sctp_stats(mib2_sctp_t *sctp)
2213 {
2214 	prval_init();
2215 	pr_sctp_rtoalgo("sctpRtoAlgorithm", sctp->sctpRtoAlgorithm);
2216 	prval("sctpRtoMin",		sctp->sctpRtoMin);
2217 	prval("sctpRtoMax",		sctp->sctpRtoMax);
2218 	prval("sctpRtoInitial",		sctp->sctpRtoInitial);
2219 	pr_int_val("sctpMaxAssocs",	sctp->sctpMaxAssocs);
2220 	prval("sctpValCookieLife",	sctp->sctpValCookieLife);
2221 	prval("sctpMaxInitRetr",	sctp->sctpMaxInitRetr);
2222 	prval("sctpCurrEstab",		sctp->sctpCurrEstab);
2223 	prval("sctpActiveEstab",	sctp->sctpActiveEstab);
2224 	prval("sctpPassiveEstab",	sctp->sctpPassiveEstab);
2225 	prval("sctpAborted",		sctp->sctpAborted);
2226 	prval("sctpShutdowns",		sctp->sctpShutdowns);
2227 	prval("sctpOutOfBlue",		sctp->sctpOutOfBlue);
2228 	prval("sctpChecksumError",	sctp->sctpChecksumError);
2229 	prval64("sctpOutCtrlChunks",	sctp->sctpOutCtrlChunks);
2230 	prval64("sctpOutOrderChunks",	sctp->sctpOutOrderChunks);
2231 	prval64("sctpOutUnorderChunks",	sctp->sctpOutUnorderChunks);
2232 	prval64("sctpRetransChunks",	sctp->sctpRetransChunks);
2233 	prval("sctpOutAck",		sctp->sctpOutAck);
2234 	prval("sctpOutAckDelayed",	sctp->sctpOutAckDelayed);
2235 	prval("sctpOutWinUpdate",	sctp->sctpOutWinUpdate);
2236 	prval("sctpOutFastRetrans",	sctp->sctpOutFastRetrans);
2237 	prval("sctpOutWinProbe",	sctp->sctpOutWinProbe);
2238 	prval64("sctpInCtrlChunks",	sctp->sctpInCtrlChunks);
2239 	prval64("sctpInOrderChunks",	sctp->sctpInOrderChunks);
2240 	prval64("sctpInUnorderChunks",	sctp->sctpInUnorderChunks);
2241 	prval("sctpInAck",		sctp->sctpInAck);
2242 	prval("sctpInDupAck",		sctp->sctpInDupAck);
2243 	prval("sctpInAckUnsent",	sctp->sctpInAckUnsent);
2244 	prval64("sctpFragUsrMsgs",	sctp->sctpFragUsrMsgs);
2245 	prval64("sctpReasmUsrMsgs",	sctp->sctpReasmUsrMsgs);
2246 	prval64("sctpOutSCTPPkts",	sctp->sctpOutSCTPPkts);
2247 	prval64("sctpInSCTPPkts",	sctp->sctpInSCTPPkts);
2248 	prval("sctpInInvalidCookie",	sctp->sctpInInvalidCookie);
2249 	prval("sctpTimRetrans",		sctp->sctpTimRetrans);
2250 	prval("sctpTimRetransDrop",	sctp->sctpTimRetransDrop);
2251 	prval("sctpTimHearBeatProbe",	sctp->sctpTimHeartBeatProbe);
2252 	prval("sctpTimHearBeatDrop",	sctp->sctpTimHeartBeatDrop);
2253 	prval("sctpListenDrop",		sctp->sctpListenDrop);
2254 	prval("sctpInClosed",		sctp->sctpInClosed);
2255 	prval_end();
2256 }
2257 
2258 static void
2259 print_tcp_stats(mib2_tcp_t *tcp)
2260 {
2261 	prval_init();
2262 	pr_int_val("tcpRtoAlgorithm",	tcp->tcpRtoAlgorithm);
2263 	pr_int_val("tcpRtoMin",		tcp->tcpRtoMin);
2264 	pr_int_val("tcpRtoMax",		tcp->tcpRtoMax);
2265 	pr_int_val("tcpMaxConn",	tcp->tcpMaxConn);
2266 	prval("tcpActiveOpens",		tcp->tcpActiveOpens);
2267 	prval("tcpPassiveOpens",	tcp->tcpPassiveOpens);
2268 	prval("tcpAttemptFails",	tcp->tcpAttemptFails);
2269 	prval("tcpEstabResets",		tcp->tcpEstabResets);
2270 	prval("tcpCurrEstab",		tcp->tcpCurrEstab);
2271 	prval64("tcpOutSegs",		tcp->tcpHCOutSegs);
2272 	prval("tcpOutDataSegs",		tcp->tcpOutDataSegs);
2273 	prval("tcpOutDataBytes",	tcp->tcpOutDataBytes);
2274 	prval("tcpRetransSegs",		tcp->tcpRetransSegs);
2275 	prval("tcpRetransBytes",	tcp->tcpRetransBytes);
2276 	prval("tcpOutAck",		tcp->tcpOutAck);
2277 	prval("tcpOutAckDelayed",	tcp->tcpOutAckDelayed);
2278 	prval("tcpOutUrg",		tcp->tcpOutUrg);
2279 	prval("tcpOutWinUpdate",	tcp->tcpOutWinUpdate);
2280 	prval("tcpOutWinProbe",		tcp->tcpOutWinProbe);
2281 	prval("tcpOutControl",		tcp->tcpOutControl);
2282 	prval("tcpOutRsts",		tcp->tcpOutRsts);
2283 	prval("tcpOutFastRetrans",	tcp->tcpOutFastRetrans);
2284 	prval64("tcpInSegs",		tcp->tcpHCInSegs);
2285 	prval_end();
2286 	prval("tcpInAckSegs",		tcp->tcpInAckSegs);
2287 	prval("tcpInAckBytes",		tcp->tcpInAckBytes);
2288 	prval("tcpInDupAck",		tcp->tcpInDupAck);
2289 	prval("tcpInAckUnsent",		tcp->tcpInAckUnsent);
2290 	prval("tcpInInorderSegs",	tcp->tcpInDataInorderSegs);
2291 	prval("tcpInInorderBytes",	tcp->tcpInDataInorderBytes);
2292 	prval("tcpInUnorderSegs",	tcp->tcpInDataUnorderSegs);
2293 	prval("tcpInUnorderBytes",	tcp->tcpInDataUnorderBytes);
2294 	prval("tcpInDupSegs",		tcp->tcpInDataDupSegs);
2295 	prval("tcpInDupBytes",		tcp->tcpInDataDupBytes);
2296 	prval("tcpInPartDupSegs",	tcp->tcpInDataPartDupSegs);
2297 	prval("tcpInPartDupBytes",	tcp->tcpInDataPartDupBytes);
2298 	prval("tcpInPastWinSegs",	tcp->tcpInDataPastWinSegs);
2299 	prval("tcpInPastWinBytes",	tcp->tcpInDataPastWinBytes);
2300 	prval("tcpInWinProbe",		tcp->tcpInWinProbe);
2301 	prval("tcpInWinUpdate",		tcp->tcpInWinUpdate);
2302 	prval("tcpInClosed",		tcp->tcpInClosed);
2303 	prval("tcpRttNoUpdate",		tcp->tcpRttNoUpdate);
2304 	prval("tcpRttUpdate",		tcp->tcpRttUpdate);
2305 	prval("tcpTimRetrans",		tcp->tcpTimRetrans);
2306 	prval("tcpTimRetransDrop",	tcp->tcpTimRetransDrop);
2307 	prval("tcpTimKeepalive",	tcp->tcpTimKeepalive);
2308 	prval("tcpTimKeepaliveProbe",	tcp->tcpTimKeepaliveProbe);
2309 	prval("tcpTimKeepaliveDrop",	tcp->tcpTimKeepaliveDrop);
2310 	prval("tcpListenDrop",		tcp->tcpListenDrop);
2311 	prval("tcpListenDropQ0",	tcp->tcpListenDropQ0);
2312 	prval("tcpHalfOpenDrop",	tcp->tcpHalfOpenDrop);
2313 	prval("tcpOutSackRetrans",	tcp->tcpOutSackRetransSegs);
2314 	prval_end();
2315 
2316 }
2317 
2318 static void
2319 print_udp_stats(mib2_udp_t *udp)
2320 {
2321 	prval_init();
2322 	prval64("udpInDatagrams",	udp->udpHCInDatagrams);
2323 	prval("udpInErrors",		udp->udpInErrors);
2324 	prval64("udpOutDatagrams",	udp->udpHCOutDatagrams);
2325 	prval("udpOutErrors",		udp->udpOutErrors);
2326 	prval_end();
2327 }
2328 
2329 static void
2330 print_rawip_stats(mib2_rawip_t *rawip)
2331 {
2332 	prval_init();
2333 	prval("rawipInDatagrams",	rawip->rawipInDatagrams);
2334 	prval("rawipInErrors",		rawip->rawipInErrors);
2335 	prval("rawipInCksumErrs",	rawip->rawipInCksumErrs);
2336 	prval("rawipOutDatagrams",	rawip->rawipOutDatagrams);
2337 	prval("rawipOutErrors",		rawip->rawipOutErrors);
2338 	prval_end();
2339 }
2340 
2341 void
2342 print_igmp_stats(struct igmpstat *igps)
2343 {
2344 	(void) printf(" %10u message%s received\n",
2345 	    igps->igps_rcv_total, PLURAL(igps->igps_rcv_total));
2346 	(void) printf(" %10u message%s received with too few bytes\n",
2347 	    igps->igps_rcv_tooshort, PLURAL(igps->igps_rcv_tooshort));
2348 	(void) printf(" %10u message%s received with bad checksum\n",
2349 	    igps->igps_rcv_badsum, PLURAL(igps->igps_rcv_badsum));
2350 	(void) printf(" %10u membership quer%s received\n",
2351 	    igps->igps_rcv_queries, PLURALY(igps->igps_rcv_queries));
2352 	(void) printf(" %10u membership quer%s received with invalid "
2353 	    "field(s)\n",
2354 	    igps->igps_rcv_badqueries, PLURALY(igps->igps_rcv_badqueries));
2355 	(void) printf(" %10u membership report%s received\n",
2356 	    igps->igps_rcv_reports, PLURAL(igps->igps_rcv_reports));
2357 	(void) printf(" %10u membership report%s received with invalid "
2358 	    "field(s)\n",
2359 	    igps->igps_rcv_badreports, PLURAL(igps->igps_rcv_badreports));
2360 	(void) printf(" %10u membership report%s received for groups to "
2361 	    "which we belong\n",
2362 	    igps->igps_rcv_ourreports, PLURAL(igps->igps_rcv_ourreports));
2363 	(void) printf(" %10u membership report%s sent\n",
2364 	    igps->igps_snd_reports, PLURAL(igps->igps_snd_reports));
2365 }
2366 
2367 static void
2368 print_mrt_stats(struct mrtstat *mrts)
2369 {
2370 	(void) puts("DVMRP multicast routing:");
2371 	(void) printf(" %10u hit%s - kernel forwarding cache hits\n",
2372 		mrts->mrts_mfc_hits, PLURAL(mrts->mrts_mfc_hits));
2373 	(void) printf(" %10u miss%s - kernel forwarding cache misses\n",
2374 		mrts->mrts_mfc_misses, PLURALES(mrts->mrts_mfc_misses));
2375 	(void) printf(" %10u packet%s potentially forwarded\n",
2376 		mrts->mrts_fwd_in, PLURAL(mrts->mrts_fwd_in));
2377 	(void) printf(" %10u packet%s actually sent out\n",
2378 		mrts->mrts_fwd_out, PLURAL(mrts->mrts_fwd_out));
2379 	(void) printf(" %10u upcall%s - upcalls made to mrouted\n",
2380 		mrts->mrts_upcalls, PLURAL(mrts->mrts_upcalls));
2381 	(void) printf(" %10u packet%s not sent out due to lack of resources\n",
2382 		mrts->mrts_fwd_drop, PLURAL(mrts->mrts_fwd_drop));
2383 	(void) printf(" %10u datagram%s with malformed tunnel options\n",
2384 		mrts->mrts_bad_tunnel, PLURAL(mrts->mrts_bad_tunnel));
2385 	(void) printf(" %10u datagram%s with no room for tunnel options\n",
2386 		mrts->mrts_cant_tunnel, PLURAL(mrts->mrts_cant_tunnel));
2387 	(void) printf(" %10u datagram%s arrived on wrong interface\n",
2388 		mrts->mrts_wrong_if, PLURAL(mrts->mrts_wrong_if));
2389 	(void) printf(" %10u datagram%s dropped due to upcall Q overflow\n",
2390 		mrts->mrts_upq_ovflw, PLURAL(mrts->mrts_upq_ovflw));
2391 	(void) printf(" %10u datagram%s cleaned up by the cache\n",
2392 		mrts->mrts_cache_cleanups, PLURAL(mrts->mrts_cache_cleanups));
2393 	(void) printf(" %10u datagram%s dropped selectively by ratelimiter\n",
2394 		mrts->mrts_drop_sel, PLURAL(mrts->mrts_drop_sel));
2395 	(void) printf(" %10u datagram%s dropped - bucket Q overflow\n",
2396 		mrts->mrts_q_overflow, PLURAL(mrts->mrts_q_overflow));
2397 	(void) printf(" %10u datagram%s dropped - larger than bkt size\n",
2398 		mrts->mrts_pkt2large, PLURAL(mrts->mrts_pkt2large));
2399 	(void) printf("\nPIM multicast routing:\n");
2400 	(void) printf(" %10u datagram%s dropped - bad version number\n",
2401 		mrts->mrts_pim_badversion, PLURAL(mrts->mrts_pim_badversion));
2402 	(void) printf(" %10u datagram%s dropped - bad checksum\n",
2403 		mrts->mrts_pim_rcv_badcsum, PLURAL(mrts->mrts_pim_rcv_badcsum));
2404 	(void) printf(" %10u datagram%s dropped - bad register packets\n",
2405 		mrts->mrts_pim_badregisters,
2406 		PLURAL(mrts->mrts_pim_badregisters));
2407 	(void) printf(
2408 		" %10u datagram%s potentially forwarded - register packets\n",
2409 		mrts->mrts_pim_regforwards, PLURAL(mrts->mrts_pim_regforwards));
2410 	(void) printf(" %10u datagram%s dropped - register send drops\n",
2411 		mrts->mrts_pim_regsend_drops,
2412 		PLURAL(mrts->mrts_pim_regsend_drops));
2413 	(void) printf(" %10u datagram%s dropped - packet malformed\n",
2414 		mrts->mrts_pim_malformed, PLURAL(mrts->mrts_pim_malformed));
2415 	(void) printf(" %10u datagram%s dropped - no memory to forward\n",
2416 		mrts->mrts_pim_nomemory, PLURAL(mrts->mrts_pim_nomemory));
2417 }
2418 
2419 static void
2420 sum_ip6_stats(mib2_ipv6IfStatsEntry_t *ip6, mib2_ipv6IfStatsEntry_t *sum6)
2421 {
2422 	/* First few are not additive */
2423 	sum6->ipv6Forwarding = ip6->ipv6Forwarding;
2424 	sum6->ipv6DefaultHopLimit = ip6->ipv6DefaultHopLimit;
2425 
2426 	sum6->ipv6InReceives += ip6->ipv6InReceives;
2427 	sum6->ipv6InHdrErrors += ip6->ipv6InHdrErrors;
2428 	sum6->ipv6InTooBigErrors += ip6->ipv6InTooBigErrors;
2429 	sum6->ipv6InNoRoutes += ip6->ipv6InNoRoutes;
2430 	sum6->ipv6InAddrErrors += ip6->ipv6InAddrErrors;
2431 	sum6->ipv6InUnknownProtos += ip6->ipv6InUnknownProtos;
2432 	sum6->ipv6InTruncatedPkts += ip6->ipv6InTruncatedPkts;
2433 	sum6->ipv6InDiscards += ip6->ipv6InDiscards;
2434 	sum6->ipv6InDelivers += ip6->ipv6InDelivers;
2435 	sum6->ipv6OutForwDatagrams += ip6->ipv6OutForwDatagrams;
2436 	sum6->ipv6OutRequests += ip6->ipv6OutRequests;
2437 	sum6->ipv6OutDiscards += ip6->ipv6OutDiscards;
2438 	sum6->ipv6OutFragOKs += ip6->ipv6OutFragOKs;
2439 	sum6->ipv6OutFragFails += ip6->ipv6OutFragFails;
2440 	sum6->ipv6OutFragCreates += ip6->ipv6OutFragCreates;
2441 	sum6->ipv6ReasmReqds += ip6->ipv6ReasmReqds;
2442 	sum6->ipv6ReasmOKs += ip6->ipv6ReasmOKs;
2443 	sum6->ipv6ReasmFails += ip6->ipv6ReasmFails;
2444 	sum6->ipv6InMcastPkts += ip6->ipv6InMcastPkts;
2445 	sum6->ipv6OutMcastPkts += ip6->ipv6OutMcastPkts;
2446 	sum6->ipv6OutNoRoutes += ip6->ipv6OutNoRoutes;
2447 	sum6->ipv6ReasmDuplicates += ip6->ipv6ReasmDuplicates;
2448 	sum6->ipv6ReasmPartDups += ip6->ipv6ReasmPartDups;
2449 	sum6->ipv6ForwProhibits += ip6->ipv6ForwProhibits;
2450 	sum6->udpInCksumErrs += ip6->udpInCksumErrs;
2451 	sum6->udpInOverflows += ip6->udpInOverflows;
2452 	sum6->rawipInOverflows += ip6->rawipInOverflows;
2453 }
2454 
2455 static void
2456 sum_icmp6_stats(mib2_ipv6IfIcmpEntry_t *icmp6, mib2_ipv6IfIcmpEntry_t *sum6)
2457 {
2458 	sum6->ipv6IfIcmpInMsgs += icmp6->ipv6IfIcmpInMsgs;
2459 	sum6->ipv6IfIcmpInErrors += icmp6->ipv6IfIcmpInErrors;
2460 	sum6->ipv6IfIcmpInDestUnreachs += icmp6->ipv6IfIcmpInDestUnreachs;
2461 	sum6->ipv6IfIcmpInAdminProhibs += icmp6->ipv6IfIcmpInAdminProhibs;
2462 	sum6->ipv6IfIcmpInTimeExcds += icmp6->ipv6IfIcmpInTimeExcds;
2463 	sum6->ipv6IfIcmpInParmProblems += icmp6->ipv6IfIcmpInParmProblems;
2464 	sum6->ipv6IfIcmpInPktTooBigs += icmp6->ipv6IfIcmpInPktTooBigs;
2465 	sum6->ipv6IfIcmpInEchos += icmp6->ipv6IfIcmpInEchos;
2466 	sum6->ipv6IfIcmpInEchoReplies += icmp6->ipv6IfIcmpInEchoReplies;
2467 	sum6->ipv6IfIcmpInRouterSolicits += icmp6->ipv6IfIcmpInRouterSolicits;
2468 	sum6->ipv6IfIcmpInRouterAdvertisements +=
2469 	    icmp6->ipv6IfIcmpInRouterAdvertisements;
2470 	sum6->ipv6IfIcmpInNeighborSolicits +=
2471 	    icmp6->ipv6IfIcmpInNeighborSolicits;
2472 	sum6->ipv6IfIcmpInNeighborAdvertisements +=
2473 	    icmp6->ipv6IfIcmpInNeighborAdvertisements;
2474 	sum6->ipv6IfIcmpInRedirects += icmp6->ipv6IfIcmpInRedirects;
2475 	sum6->ipv6IfIcmpInGroupMembQueries +=
2476 	    icmp6->ipv6IfIcmpInGroupMembQueries;
2477 	sum6->ipv6IfIcmpInGroupMembResponses +=
2478 	    icmp6->ipv6IfIcmpInGroupMembResponses;
2479 	sum6->ipv6IfIcmpInGroupMembReductions +=
2480 	    icmp6->ipv6IfIcmpInGroupMembReductions;
2481 	sum6->ipv6IfIcmpOutMsgs += icmp6->ipv6IfIcmpOutMsgs;
2482 	sum6->ipv6IfIcmpOutErrors += icmp6->ipv6IfIcmpOutErrors;
2483 	sum6->ipv6IfIcmpOutDestUnreachs += icmp6->ipv6IfIcmpOutDestUnreachs;
2484 	sum6->ipv6IfIcmpOutAdminProhibs += icmp6->ipv6IfIcmpOutAdminProhibs;
2485 	sum6->ipv6IfIcmpOutTimeExcds += icmp6->ipv6IfIcmpOutTimeExcds;
2486 	sum6->ipv6IfIcmpOutParmProblems += icmp6->ipv6IfIcmpOutParmProblems;
2487 	sum6->ipv6IfIcmpOutPktTooBigs += icmp6->ipv6IfIcmpOutPktTooBigs;
2488 	sum6->ipv6IfIcmpOutEchos += icmp6->ipv6IfIcmpOutEchos;
2489 	sum6->ipv6IfIcmpOutEchoReplies += icmp6->ipv6IfIcmpOutEchoReplies;
2490 	sum6->ipv6IfIcmpOutRouterSolicits +=
2491 	    icmp6->ipv6IfIcmpOutRouterSolicits;
2492 	sum6->ipv6IfIcmpOutRouterAdvertisements +=
2493 	    icmp6->ipv6IfIcmpOutRouterAdvertisements;
2494 	sum6->ipv6IfIcmpOutNeighborSolicits +=
2495 	    icmp6->ipv6IfIcmpOutNeighborSolicits;
2496 	sum6->ipv6IfIcmpOutNeighborAdvertisements +=
2497 	    icmp6->ipv6IfIcmpOutNeighborAdvertisements;
2498 	sum6->ipv6IfIcmpOutRedirects += icmp6->ipv6IfIcmpOutRedirects;
2499 	sum6->ipv6IfIcmpOutGroupMembQueries +=
2500 	    icmp6->ipv6IfIcmpOutGroupMembQueries;
2501 	sum6->ipv6IfIcmpOutGroupMembResponses +=
2502 	    icmp6->ipv6IfIcmpOutGroupMembResponses;
2503 	sum6->ipv6IfIcmpOutGroupMembReductions +=
2504 	    icmp6->ipv6IfIcmpOutGroupMembReductions;
2505 	sum6->ipv6IfIcmpInOverflows += icmp6->ipv6IfIcmpInOverflows;
2506 }
2507 
2508 /* ----------------------------- MRT_STAT_REPORT --------------------------- */
2509 
2510 static void
2511 mrt_stat_report(mib_item_t *curritem)
2512 {
2513 	int	jtemp = 0;
2514 	mib_item_t *tempitem;
2515 
2516 	if (!(family_selected(AF_INET)))
2517 		return;
2518 
2519 	(void) putchar('\n');
2520 	/* 'for' loop 1: */
2521 	for (tempitem = curritem;
2522 	    tempitem;
2523 	    tempitem = tempitem->next_item) {
2524 		if (Dflag) {
2525 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
2526 			(void) printf("Group = %d, mib_id = %d, "
2527 			    "length = %d, valp = 0x%p\n",
2528 			    tempitem->group, tempitem->mib_id,
2529 			    tempitem->length, tempitem->valp);
2530 		}
2531 
2532 		if (tempitem->mib_id == 0) {
2533 			switch (tempitem->group) {
2534 			case EXPER_DVMRP: {
2535 				struct mrtstat	*mrts;
2536 				mrts = (struct mrtstat *)tempitem->valp;
2537 
2538 				if (!(family_selected(AF_INET)))
2539 					continue; /* 'for' loop 1 */
2540 
2541 				print_mrt_stats(mrts);
2542 				break;
2543 			}
2544 			}
2545 		}
2546 	} /* 'for' loop 1 ends */
2547 	(void) putchar('\n');
2548 	(void) fflush(stdout);
2549 }
2550 
2551 /*
2552  * if_stat_total() - Computes totals for interface statistics
2553  *                   and returns result by updating sumstats.
2554  */
2555 static void
2556 if_stat_total(struct ifstat *oldstats, struct ifstat *newstats,
2557     struct ifstat *sumstats)
2558 {
2559 	sumstats->ipackets += newstats->ipackets - oldstats->ipackets;
2560 	sumstats->opackets += newstats->opackets - oldstats->opackets;
2561 	sumstats->ierrors += newstats->ierrors - oldstats->ierrors;
2562 	sumstats->oerrors += newstats->oerrors - oldstats->oerrors;
2563 	sumstats->collisions += newstats->collisions - oldstats->collisions;
2564 }
2565 
2566 /* --------------------- IF_REPORT (netstat -i)  -------------------------- */
2567 
2568 static struct	ifstat	zerostat = {
2569 	0LL, 0LL, 0LL, 0LL, 0LL
2570 };
2571 
2572 static void
2573 if_report(mib_item_t *item, char *matchname,
2574     int Iflag_only, boolean_t once_only)
2575 {
2576 	static boolean_t	reentry = B_FALSE;
2577 	boolean_t		alreadydone = B_FALSE;
2578 	int			jtemp = 0;
2579 	uint32_t		ifindex_v4 = 0;
2580 	uint32_t		ifindex_v6 = 0;
2581 
2582 	/* 'for' loop 1: */
2583 	for (; item; item = item->next_item) {
2584 		if (Dflag) {
2585 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
2586 			(void) printf("Group = %d, mib_id = %d, "
2587 			    "length = %d, valp = 0x%p\n",
2588 			    item->group, item->mib_id, item->length,
2589 			    item->valp);
2590 		}
2591 
2592 		switch (item->group) {
2593 		case MIB2_IP:
2594 		if (item->mib_id != MIB2_IP_ADDR ||
2595 		    !family_selected(AF_INET))
2596 			continue; /* 'for' loop 1 */
2597 		{
2598 			static struct ifstat	old = {0L, 0L, 0L, 0L, 0L};
2599 			static struct ifstat	new = {0L, 0L, 0L, 0L, 0L};
2600 			struct ifstat		sum;
2601 			struct iflist		*newlist = NULL;
2602 			static struct iflist	*oldlist = NULL;
2603 			kstat_t	 *ksp;
2604 
2605 			if (once_only) {
2606 				char    ifname[LIFNAMSIZ + 1];
2607 				char    logintname[LIFNAMSIZ + 1];
2608 				mib2_ipAddrEntry_t *ap;
2609 				struct ifstat	stat = {0L, 0L, 0L, 0L, 0L};
2610 				boolean_t	first = B_TRUE;
2611 				uint32_t	new_ifindex;
2612 
2613 				if (Dflag)
2614 					(void) printf("if_report: %d items\n",
2615 					    (item->length)
2616 					    / sizeof (mib2_ipAddrEntry_t));
2617 
2618 				/* 'for' loop 2a: */
2619 				for (ap = (mib2_ipAddrEntry_t *)item->valp;
2620 				    (char *)ap < (char *)item->valp
2621 				    + item->length;
2622 				    ap++) {
2623 					(void) octetstr(&ap->ipAdEntIfIndex,
2624 					    'a', logintname,
2625 					    sizeof (logintname));
2626 					(void) strcpy(ifname, logintname);
2627 					(void) strtok(ifname, ":");
2628 					if (matchname != NULL &&
2629 					    strcmp(matchname, ifname) != 0 &&
2630 					    strcmp(matchname, logintname) != 0)
2631 						continue; /* 'for' loop 2a */
2632 					new_ifindex =
2633 					    if_nametoindex(logintname);
2634 					if (new_ifindex != ifindex_v4 &&
2635 					    (ksp = kstat_lookup(kc, NULL, -1,
2636 					    ifname)) != NULL) {
2637 						(void) safe_kstat_read(kc, ksp,
2638 						    NULL);
2639 						stat.ipackets =
2640 						    kstat_named_value(ksp,
2641 						    "ipackets");
2642 						stat.ierrors =
2643 						    kstat_named_value(ksp,
2644 						    "ierrors");
2645 						stat.opackets =
2646 						    kstat_named_value(ksp,
2647 						    "opackets");
2648 						stat.oerrors =
2649 						    kstat_named_value(ksp,
2650 						    "oerrors");
2651 						stat.collisions =
2652 						    kstat_named_value(ksp,
2653 						    "collisions");
2654 						if (first) {
2655 						(void) printf(
2656 						    "%-5.5s %-5.5s%-13.13s "
2657 						    "%-14.14s %-6.6s %-5.5s "
2658 						    "%-6.6s %-5.5s %-6.6s "
2659 						    "%-6.6s\n",
2660 						    "Name", "Mtu", "Net/Dest",
2661 						    "Address", "Ipkts",
2662 						    "Ierrs", "Opkts", "Oerrs",
2663 						    "Collis", "Queue");
2664 						first = B_FALSE;
2665 						}
2666 						if_report_ip4(ap, ifname,
2667 						    logintname, &stat, B_TRUE);
2668 						ifindex_v4 = new_ifindex;
2669 					} else {
2670 						if_report_ip4(ap, ifname,
2671 						    logintname, &stat, B_FALSE);
2672 					}
2673 				} /* 'for' loop 2a ends */
2674 				if (!first)
2675 					(void) putchar('\n');
2676 			} else if (!alreadydone) {
2677 				char    ifname[LIFNAMSIZ + 1];
2678 				char    buf[LIFNAMSIZ + 1];
2679 				mib2_ipAddrEntry_t *ap;
2680 				struct ifstat   t;
2681 				struct iflist	*tlp = NULL;
2682 				struct iflist	**nextnew = &newlist;
2683 				struct iflist	*walkold;
2684 				struct iflist	*cleanlist;
2685 				boolean_t	found_if = B_FALSE;
2686 
2687 				alreadydone = B_TRUE; /* ignore other case */
2688 
2689 				/*
2690 				 * Check if there is anything to do.
2691 				 */
2692 				if (item->length <
2693 				    sizeof (mib2_ipAddrEntry_t)) {
2694 					fail(0, "No compatible interfaces");
2695 				}
2696 
2697 				/*
2698 				 * 'for' loop 2b: find the "right" entry:
2699 				 * If an interface name to match has been
2700 				 * supplied then try and find it, otherwise
2701 				 * match the first non-loopback interface found.
2702 				 * Use lo0 if all else fails.
2703 				 */
2704 				for (ap = (mib2_ipAddrEntry_t *)item->valp;
2705 				    (char *)ap < (char *)item->valp
2706 				    + item->length;
2707 				    ap++) {
2708 					(void) octetstr(&ap->ipAdEntIfIndex,
2709 					'a', ifname, sizeof (ifname));
2710 					(void) strtok(ifname, ":");
2711 
2712 					if (matchname) {
2713 						if (strcmp(matchname,
2714 						    ifname) == 0) {
2715 							/* 'for' loop 2b */
2716 							found_if = B_TRUE;
2717 							break;
2718 						}
2719 					} else if (strcmp(ifname, "lo0") != 0)
2720 						break; /* 'for' loop 2b */
2721 				} /* 'for' loop 2b ends */
2722 
2723 				if (matchname == NULL) {
2724 					matchname = ifname;
2725 				} else {
2726 					if (!found_if)
2727 						fail(0, "-I: %s no such "
2728 						    "interface.", matchname);
2729 				}
2730 
2731 				if (Iflag_only == 0 || !reentry) {
2732 					(void) printf("    input   %-6.6s    "
2733 					    "output	",
2734 					    matchname);
2735 					(void) printf("   input  (Total)    "
2736 					"output\n");
2737 					(void) printf("%-7.7s %-5.5s %-7.7s "
2738 					    "%-5.5s %-6.6s ",
2739 					    "packets", "errs", "packets",
2740 					    "errs", "colls");
2741 					(void) printf("%-7.7s %-5.5s %-7.7s "
2742 					    "%-5.5s %-6.6s\n",
2743 					    "packets", "errs", "packets",
2744 					    "errs", "colls");
2745 				}
2746 
2747 				sum = zerostat;
2748 
2749 				/* 'for' loop 2c: */
2750 				for (ap = (mib2_ipAddrEntry_t *)item->valp;
2751 				    (char *)ap < (char *)item->valp
2752 				    + item->length;
2753 				    ap++) {
2754 					(void) octetstr(&ap->ipAdEntIfIndex,
2755 					    'a', buf, sizeof (buf));
2756 					(void) strtok(buf, ":");
2757 
2758 					/*
2759 					 * We have reduced the IP interface
2760 					 * name, which could have been a
2761 					 * logical, down to a name suitable
2762 					 * for use with kstats.
2763 					 * We treat this name as unique and
2764 					 * only collate statistics for it once
2765 					 * per pass. This is to avoid falsely
2766 					 * amplifying these statistics by the
2767 					 * the number of logical instances.
2768 					 */
2769 					if ((tlp != NULL) &&
2770 					    ((strcmp(buf, tlp->ifname) == 0))) {
2771 						continue;
2772 					}
2773 
2774 					ksp = kstat_lookup(kc, NULL, -1, buf);
2775 					if (ksp &&
2776 					    ksp->ks_type == KSTAT_TYPE_NAMED)
2777 						(void) safe_kstat_read(kc, ksp,
2778 						    NULL);
2779 
2780 					t.ipackets = kstat_named_value(ksp,
2781 					    "ipackets");
2782 					t.ierrors = kstat_named_value(ksp,
2783 					    "ierrors");
2784 					t.opackets = kstat_named_value(ksp,
2785 					    "opackets");
2786 					t.oerrors = kstat_named_value(ksp,
2787 					    "oerrors");
2788 					t.collisions = kstat_named_value(ksp,
2789 					    "collisions");
2790 
2791 					if (strcmp(buf, matchname) == 0)
2792 						new = t;
2793 
2794 					/* Build the interface list */
2795 
2796 					tlp = malloc(sizeof (struct iflist));
2797 					(void) strlcpy(tlp->ifname, buf,
2798 					    sizeof (tlp->ifname));
2799 					tlp->tot = t;
2800 					*nextnew = tlp;
2801 					nextnew = &tlp->next_if;
2802 
2803 					/*
2804 					 * First time through.
2805 					 * Just add up the interface stats.
2806 					 */
2807 
2808 					if (oldlist == NULL) {
2809 						if_stat_total(&zerostat,
2810 						    &t, &sum);
2811 						continue;
2812 					}
2813 
2814 					/*
2815 					 * Walk old list for the interface.
2816 					 *
2817 					 * If found, add difference to total.
2818 					 *
2819 					 * If not, an interface has been plumbed
2820 					 * up.  In this case, we will simply
2821 					 * ignore the new interface until the
2822 					 * next interval; as there's no easy way
2823 					 * to acquire statistics between time
2824 					 * of the plumb and the next interval
2825 					 * boundary.  This results in inaccurate
2826 					 * total values for current interval.
2827 					 *
2828 					 * Note the case when an interface is
2829 					 * unplumbed; as similar problems exist.
2830 					 * The unplumbed interface is not in the
2831 					 * current list, and there's no easy way
2832 					 * to account for the statistics between
2833 					 * the previous interval and time of the
2834 					 * unplumb.  Therefore, we (in a sense)
2835 					 * ignore the removed interface by only
2836 					 * involving "current" interfaces when
2837 					 * computing the total statistics.
2838 					 * Unfortunately, this also results in
2839 					 * inaccurate values for interval total.
2840 					 */
2841 
2842 					for (walkold = oldlist;
2843 					    walkold != NULL;
2844 					    walkold = walkold->next_if) {
2845 						if (strcmp(walkold->ifname,
2846 						    buf) == 0) {
2847 							if_stat_total(
2848 							    &walkold->tot,
2849 							    &t, &sum);
2850 							break;
2851 						}
2852 					}
2853 
2854 				} /* 'for' loop 2c ends */
2855 
2856 				*nextnew = NULL;
2857 
2858 				(void) printf("%-7llu %-5llu %-7llu "
2859 				    "%-5llu %-6llu ",
2860 				    new.ipackets - old.ipackets,
2861 				    new.ierrors - old.ierrors,
2862 				    new.opackets - old.opackets,
2863 				    new.oerrors - old.oerrors,
2864 				    new.collisions - old.collisions);
2865 
2866 				(void) printf("%-7llu %-5llu %-7llu "
2867 				    "%-5llu %-6llu\n", sum.ipackets,
2868 				    sum.ierrors, sum.opackets,
2869 				    sum.oerrors, sum.collisions);
2870 
2871 				/*
2872 				 * Tidy things up once finished.
2873 				 */
2874 
2875 				old = new;
2876 				cleanlist = oldlist;
2877 				oldlist = newlist;
2878 				while (cleanlist != NULL) {
2879 					tlp = cleanlist->next_if;
2880 					free(cleanlist);
2881 					cleanlist = tlp;
2882 				}
2883 			}
2884 			break;
2885 		}
2886 		case MIB2_IP6:
2887 		if (item->mib_id != MIB2_IP6_ADDR ||
2888 		    !family_selected(AF_INET6))
2889 			continue; /* 'for' loop 1 */
2890 		{
2891 			static struct ifstat	old6 = {0L, 0L, 0L, 0L, 0L};
2892 			static struct ifstat	new6 = {0L, 0L, 0L, 0L, 0L};
2893 			struct ifstat		sum6;
2894 			struct iflist		*newlist6 = NULL;
2895 			static struct iflist	*oldlist6 = NULL;
2896 			kstat_t	 *ksp;
2897 
2898 			if (once_only) {
2899 				char    ifname[LIFNAMSIZ + 1];
2900 				char    logintname[LIFNAMSIZ + 1];
2901 				mib2_ipv6AddrEntry_t *ap6;
2902 				struct ifstat	stat = {0L, 0L, 0L, 0L, 0L};
2903 				boolean_t	first = B_TRUE;
2904 				uint32_t	new_ifindex;
2905 
2906 				if (Dflag)
2907 					(void) printf("if_report: %d items\n",
2908 					    (item->length)
2909 					    / sizeof (mib2_ipv6AddrEntry_t));
2910 				/* 'for' loop 2d: */
2911 				for (ap6 = (mib2_ipv6AddrEntry_t *)item->valp;
2912 				    (char *)ap6 < (char *)item->valp
2913 				    + item->length;
2914 				    ap6++) {
2915 					(void) octetstr(&ap6->ipv6AddrIfIndex,
2916 					    'a', logintname,
2917 					    sizeof (logintname));
2918 					(void) strcpy(ifname, logintname);
2919 					(void) strtok(ifname, ":");
2920 					if (matchname != NULL &&
2921 					    strcmp(matchname, ifname) != 0 &&
2922 					    strcmp(matchname, logintname) != 0)
2923 						continue; /* 'for' loop 2d */
2924 					new_ifindex =
2925 					    if_nametoindex(logintname);
2926 					if (new_ifindex != ifindex_v6 &&
2927 					    (ksp = kstat_lookup(kc, NULL, -1,
2928 					    ifname)) != NULL) {
2929 						(void) safe_kstat_read(kc, ksp,
2930 						    NULL);
2931 						stat.ipackets =
2932 						    kstat_named_value(ksp,
2933 						    "ipackets");
2934 						stat.ierrors =
2935 						    kstat_named_value(ksp,
2936 						    "ierrors");
2937 						stat.opackets =
2938 						    kstat_named_value(ksp,
2939 						    "opackets");
2940 						stat.oerrors =
2941 						    kstat_named_value(ksp,
2942 						    "oerrors");
2943 						stat.collisions =
2944 						    kstat_named_value(ksp,
2945 						    "collisions");
2946 						if (first) {
2947 							(void) printf(
2948 							    "%-5.5s %-5.5s%"
2949 							    "-27.27s %-27.27s "
2950 							    "%-6.6s %-5.5s "
2951 							    "%-6.6s %-5.5s "
2952 							    "%-6.6s\n",
2953 							    "Name", "Mtu",
2954 							    "Net/Dest",
2955 							    "Address", "Ipkts",
2956 							    "Ierrs", "Opkts",
2957 							    "Oerrs", "Collis");
2958 							first = B_FALSE;
2959 						}
2960 						if_report_ip6(ap6, ifname,
2961 						    logintname, &stat, B_TRUE);
2962 						ifindex_v6 = new_ifindex;
2963 					} else {
2964 						if_report_ip6(ap6, ifname,
2965 						    logintname, &stat, B_FALSE);
2966 					}
2967 				} /* 'for' loop 2d ends */
2968 				if (!first)
2969 					(void) putchar('\n');
2970 			} else if (!alreadydone) {
2971 				char    ifname[LIFNAMSIZ + 1];
2972 				char    buf[IFNAMSIZ + 1];
2973 				mib2_ipv6AddrEntry_t *ap6;
2974 				struct ifstat   t;
2975 				struct iflist	*tlp = NULL;
2976 				struct iflist	**nextnew = &newlist6;
2977 				struct iflist	*walkold;
2978 				struct iflist	*cleanlist;
2979 				boolean_t	found_if = B_FALSE;
2980 
2981 				alreadydone = B_TRUE; /* ignore other case */
2982 
2983 				/*
2984 				 * Check if there is anything to do.
2985 				 */
2986 				if (item->length <
2987 				    sizeof (mib2_ipv6AddrEntry_t)) {
2988 					fail(0, "No compatible interfaces");
2989 				}
2990 
2991 				/*
2992 				 * 'for' loop 2e: find the "right" entry:
2993 				 * If an interface name to match has been
2994 				 * supplied then try and find it, otherwise
2995 				 * match the first non-loopback interface found.
2996 				 * Use lo0 if all else fails.
2997 				 */
2998 				for (ap6 = (mib2_ipv6AddrEntry_t *)item->valp;
2999 				    (char *)ap6 < (char *)item->valp
3000 				    + item->length;
3001 				    ap6++) {
3002 					(void) octetstr(&ap6->ipv6AddrIfIndex,
3003 					    'a', ifname, sizeof (ifname));
3004 					(void) strtok(ifname, ":");
3005 
3006 					if (matchname) {
3007 						if (strcmp(matchname,
3008 						    ifname) == 0) {
3009 							/* 'for' loop 2e */
3010 							found_if = B_TRUE;
3011 							break;
3012 						}
3013 					} else if (strcmp(ifname, "lo0") != 0)
3014 						break; /* 'for' loop 2e */
3015 				} /* 'for' loop 2e ends */
3016 
3017 				if (matchname == NULL) {
3018 					matchname = ifname;
3019 				} else {
3020 					if (!found_if)
3021 						fail(0, "-I: %s no such "
3022 						    "interface.", matchname);
3023 				}
3024 
3025 				if (Iflag_only == 0 || !reentry) {
3026 					(void) printf(
3027 					    "    input   %-6.6s"
3028 					    "    output	",
3029 					    matchname);
3030 					(void) printf("   input  (Total)"
3031 					    "    output\n");
3032 					(void) printf("%-7.7s %-5.5s %-7.7s "
3033 					    "%-5.5s %-6.6s ",
3034 					    "packets", "errs", "packets",
3035 					    "errs", "colls");
3036 					(void) printf("%-7.7s %-5.5s %-7.7s "
3037 					    "%-5.5s %-6.6s\n",
3038 					    "packets", "errs", "packets",
3039 					    "errs", "colls");
3040 				}
3041 
3042 				sum6 = zerostat;
3043 
3044 				/* 'for' loop 2f: */
3045 				for (ap6 = (mib2_ipv6AddrEntry_t *)item->valp;
3046 				    (char *)ap6 < (char *)item->valp
3047 				    + item->length;
3048 				    ap6++) {
3049 					(void) octetstr(&ap6->ipv6AddrIfIndex,
3050 					    'a', buf, sizeof (buf));
3051 					(void) strtok(buf, ":");
3052 
3053 					/*
3054 					 * We have reduced the IP interface
3055 					 * name, which could have been a
3056 					 * logical, down to a name suitable
3057 					 * for use with kstats.
3058 					 * We treat this name as unique and
3059 					 * only collate statistics for it once
3060 					 * per pass. This is to avoid falsely
3061 					 * amplifying these statistics by the
3062 					 * the number of logical instances.
3063 					 */
3064 
3065 					if ((tlp != NULL) &&
3066 					    ((strcmp(buf, tlp->ifname) == 0))) {
3067 						continue;
3068 					}
3069 
3070 					ksp = kstat_lookup(kc, NULL, -1, buf);
3071 					if (ksp && ksp->ks_type ==
3072 					    KSTAT_TYPE_NAMED)
3073 						(void) safe_kstat_read(kc,
3074 						    ksp, NULL);
3075 
3076 					t.ipackets = kstat_named_value(ksp,
3077 					    "ipackets");
3078 					t.ierrors = kstat_named_value(ksp,
3079 					    "ierrors");
3080 					t.opackets = kstat_named_value(ksp,
3081 					    "opackets");
3082 					t.oerrors = kstat_named_value(ksp,
3083 					    "oerrors");
3084 					t.collisions = kstat_named_value(ksp,
3085 					    "collisions");
3086 
3087 					if (strcmp(buf, matchname) == 0)
3088 						new6 = t;
3089 
3090 					/* Build the interface list */
3091 
3092 					tlp = malloc(sizeof (struct iflist));
3093 					(void) strlcpy(tlp->ifname, buf,
3094 					    sizeof (tlp->ifname));
3095 					tlp->tot = t;
3096 					*nextnew = tlp;
3097 					nextnew = &tlp->next_if;
3098 
3099 					/*
3100 					 * First time through.
3101 					 * Just add up the interface stats.
3102 					 */
3103 
3104 					if (oldlist6 == NULL) {
3105 						if_stat_total(&zerostat,
3106 						    &t, &sum6);
3107 						continue;
3108 					}
3109 
3110 					/*
3111 					 * Walk old list for the interface.
3112 					 *
3113 					 * If found, add difference to total.
3114 					 *
3115 					 * If not, an interface has been plumbed
3116 					 * up.  In this case, we will simply
3117 					 * ignore the new interface until the
3118 					 * next interval; as there's no easy way
3119 					 * to acquire statistics between time
3120 					 * of the plumb and the next interval
3121 					 * boundary.  This results in inaccurate
3122 					 * total values for current interval.
3123 					 *
3124 					 * Note the case when an interface is
3125 					 * unplumbed; as similar problems exist.
3126 					 * The unplumbed interface is not in the
3127 					 * current list, and there's no easy way
3128 					 * to account for the statistics between
3129 					 * the previous interval and time of the
3130 					 * unplumb.  Therefore, we (in a sense)
3131 					 * ignore the removed interface by only
3132 					 * involving "current" interfaces when
3133 					 * computing the total statistics.
3134 					 * Unfortunately, this also results in
3135 					 * inaccurate values for interval total.
3136 					 */
3137 
3138 					for (walkold = oldlist6;
3139 					    walkold != NULL;
3140 					    walkold = walkold->next_if) {
3141 						if (strcmp(walkold->ifname,
3142 						    buf) == 0) {
3143 							if_stat_total(
3144 							    &walkold->tot,
3145 							    &t, &sum6);
3146 							break;
3147 						}
3148 					}
3149 
3150 				} /* 'for' loop 2f ends */
3151 
3152 				*nextnew = NULL;
3153 
3154 				(void) printf("%-7llu %-5llu %-7llu "
3155 				    "%-5llu %-6llu ",
3156 				    new6.ipackets - old6.ipackets,
3157 				    new6.ierrors - old6.ierrors,
3158 				    new6.opackets - old6.opackets,
3159 				    new6.oerrors - old6.oerrors,
3160 				    new6.collisions - old6.collisions);
3161 
3162 				(void) printf("%-7llu %-5llu %-7llu "
3163 				    "%-5llu %-6llu\n", sum6.ipackets,
3164 				    sum6.ierrors, sum6.opackets,
3165 				    sum6.oerrors, sum6.collisions);
3166 
3167 				/*
3168 				 * Tidy things up once finished.
3169 				 */
3170 
3171 				old6 = new6;
3172 				cleanlist = oldlist6;
3173 				oldlist6 = newlist6;
3174 				while (cleanlist != NULL) {
3175 					tlp = cleanlist->next_if;
3176 					free(cleanlist);
3177 					cleanlist = tlp;
3178 				}
3179 			}
3180 			break;
3181 		}
3182 		}
3183 		if (Iflag_only == 0)
3184 		    (void) putchar('\n');
3185 		(void) fflush(stdout);
3186 	} /* 'for' loop 1 ends */
3187 	reentry = B_TRUE;
3188 }
3189 
3190 static void
3191 if_report_ip4(mib2_ipAddrEntry_t *ap,
3192 	char ifname[], char logintname[], struct ifstat *statptr,
3193 	boolean_t ksp_not_null) {
3194 
3195 	char abuf[MAXHOSTNAMELEN + 1];
3196 	char dstbuf[MAXHOSTNAMELEN + 1];
3197 
3198 	if (ksp_not_null) {
3199 		(void) printf("%-5s %-5u",
3200 		    ifname, ap->ipAdEntInfo.ae_mtu);
3201 		if (ap->ipAdEntInfo.ae_flags & IFF_POINTOPOINT)
3202 			(void) pr_addr(ap->ipAdEntInfo.ae_pp_dst_addr,
3203 			    abuf, sizeof (abuf));
3204 		else
3205 			(void) pr_netaddr(ap->ipAdEntAddr,
3206 			    ap->ipAdEntNetMask, abuf, sizeof (abuf));
3207 		(void) printf("%-13s %-14s %-6llu %-5llu %-6llu %-5llu "
3208 		    "%-6llu %-6llu\n",
3209 		    abuf, pr_addr(ap->ipAdEntAddr, dstbuf, sizeof (dstbuf)),
3210 		    statptr->ipackets, statptr->ierrors,
3211 		    statptr->opackets, statptr->oerrors,
3212 		    statptr->collisions, 0LL);
3213 	}
3214 	/*
3215 	 * Print logical interface info if Aflag set (including logical unit 0)
3216 	 */
3217 	if (Aflag) {
3218 		*statptr = zerostat;
3219 		statptr->ipackets = ap->ipAdEntInfo.ae_ibcnt;
3220 		statptr->opackets = ap->ipAdEntInfo.ae_obcnt;
3221 
3222 		(void) printf("%-5s %-5u", logintname, ap->ipAdEntInfo.ae_mtu);
3223 		if (ap->ipAdEntInfo.ae_flags & IFF_POINTOPOINT)
3224 			(void) pr_addr(ap->ipAdEntInfo.ae_pp_dst_addr, abuf,
3225 			sizeof (abuf));
3226 		else
3227 			(void) pr_netaddr(ap->ipAdEntAddr, ap->ipAdEntNetMask,
3228 			    abuf, sizeof (abuf));
3229 
3230 		(void) printf("%-13s %-14s %-6llu %-5s %-6llu "
3231 		    "%-5s %-6s %-6llu\n", abuf,
3232 		    pr_addr(ap->ipAdEntAddr, dstbuf, sizeof (dstbuf)),
3233 		    statptr->ipackets, "N/A", statptr->opackets, "N/A", "N/A",
3234 		    0LL);
3235 	}
3236 }
3237 
3238 static void
3239 if_report_ip6(mib2_ipv6AddrEntry_t *ap6,
3240 	char ifname[], char logintname[], struct ifstat *statptr,
3241 	boolean_t ksp_not_null) {
3242 
3243 	char abuf[MAXHOSTNAMELEN + 1];
3244 	char dstbuf[MAXHOSTNAMELEN + 1];
3245 
3246 	if (ksp_not_null) {
3247 		(void) printf("%-5s %-5u", ifname, ap6->ipv6AddrInfo.ae_mtu);
3248 		if (ap6->ipv6AddrInfo.ae_flags &
3249 		    IFF_POINTOPOINT) {
3250 			(void) pr_addr6(&ap6->ipv6AddrInfo.ae_pp_dst_addr,
3251 			    abuf, sizeof (abuf));
3252 		} else {
3253 			(void) pr_prefix6(&ap6->ipv6AddrAddress,
3254 			    ap6->ipv6AddrPfxLength, abuf,
3255 			    sizeof (abuf));
3256 		}
3257 		(void) printf("%-27s %-27s %-6llu %-5llu "
3258 		    "%-6llu %-5llu %-6llu\n",
3259 		    abuf, pr_addr6(&ap6->ipv6AddrAddress, dstbuf,
3260 		    sizeof (dstbuf)),
3261 		    statptr->ipackets, statptr->ierrors, statptr->opackets,
3262 		    statptr->oerrors, statptr->collisions);
3263 	}
3264 	/*
3265 	 * Print logical interface info if Aflag set (including logical unit 0)
3266 	 */
3267 	if (Aflag) {
3268 		*statptr = zerostat;
3269 		statptr->ipackets = ap6->ipv6AddrInfo.ae_ibcnt;
3270 		statptr->opackets = ap6->ipv6AddrInfo.ae_obcnt;
3271 
3272 		(void) printf("%-5s %-5u", logintname,
3273 		    ap6->ipv6AddrInfo.ae_mtu);
3274 		if (ap6->ipv6AddrInfo.ae_flags & IFF_POINTOPOINT)
3275 			(void) pr_addr6(&ap6->ipv6AddrInfo.ae_pp_dst_addr,
3276 			    abuf, sizeof (abuf));
3277 		else
3278 			(void) pr_prefix6(&ap6->ipv6AddrAddress,
3279 			    ap6->ipv6AddrPfxLength, abuf, sizeof (abuf));
3280 		(void) printf("%-27s %-27s %-6llu %-5s %-6llu %-5s %-6s\n",
3281 		    abuf, pr_addr6(&ap6->ipv6AddrAddress, dstbuf,
3282 		    sizeof (dstbuf)),
3283 		    statptr->ipackets, "N/A",
3284 		    statptr->opackets, "N/A", "N/A");
3285 	}
3286 }
3287 
3288 /* --------------------- DHCP_REPORT  (netstat -D) ------------------------- */
3289 
3290 static boolean_t
3291 dhcp_do_ipc(dhcp_ipc_type_t type, const char *ifname, boolean_t printed_one)
3292 {
3293 	dhcp_ipc_request_t	*request;
3294 	dhcp_ipc_reply_t	*reply;
3295 	int			error;
3296 
3297 	request = dhcp_ipc_alloc_request(type, ifname, NULL, 0, DHCP_TYPE_NONE);
3298 	if (request == NULL)
3299 		fail(0, "dhcp_do_ipc: out of memory");
3300 
3301 	error = dhcp_ipc_make_request(request, &reply, DHCP_IPC_WAIT_DEFAULT);
3302 	if (error != 0) {
3303 		free(request);
3304 		fail(0, "dhcp_do_ipc: %s", dhcp_ipc_strerror(error));
3305 	}
3306 
3307 	free(request);
3308 	error = reply->return_code;
3309 	if (error == DHCP_IPC_E_UNKIF) {
3310 		free(reply);
3311 		return (printed_one);
3312 	}
3313 	if (error != 0) {
3314 		free(reply);
3315 		fail(0, "dhcp_do_ipc: %s", dhcp_ipc_strerror(error));
3316 	}
3317 
3318 	if (!printed_one)
3319 		(void) printf("%s", dhcp_status_hdr_string());
3320 
3321 	(void) printf("%s", dhcp_status_reply_to_string(reply));
3322 	free(reply);
3323 	return (B_TRUE);
3324 }
3325 
3326 /*
3327  * dhcp_walk_interfaces: walk the list of interfaces that have a given set of
3328  * flags turned on (flags_on) and a given set turned off (flags_off) for a
3329  * given address family (af).  For each, print out the DHCP status using
3330  * dhcp_do_ipc.
3331  */
3332 static boolean_t
3333 dhcp_walk_interfaces(uint_t flags_on, uint_t flags_off, int af,
3334     boolean_t printed_one)
3335 {
3336 	struct lifnum	lifn;
3337 	struct lifconf	lifc;
3338 	int		n_ifs, i, sock_fd;
3339 
3340 	sock_fd = socket(af, SOCK_DGRAM, 0);
3341 	if (sock_fd == -1)
3342 		return (printed_one);
3343 
3344 	/*
3345 	 * SIOCGLIFNUM is just an estimate.  If the ioctl fails, we don't care;
3346 	 * just drive on and use SIOCGLIFCONF with increasing buffer sizes, as
3347 	 * is traditional.
3348 	 */
3349 	(void) memset(&lifn, 0, sizeof (lifn));
3350 	lifn.lifn_family = af;
3351 	lifn.lifn_flags = LIFC_ALLZONES | LIFC_NOXMIT;
3352 	if (ioctl(sock_fd, SIOCGLIFNUM, &lifn) == -1)
3353 		n_ifs = LIFN_GUARD_VALUE;
3354 	else
3355 		n_ifs = lifn.lifn_count + LIFN_GUARD_VALUE;
3356 
3357 	(void) memset(&lifc, 0, sizeof (lifc));
3358 	lifc.lifc_family = af;
3359 	lifc.lifc_flags = lifn.lifn_flags;
3360 	lifc.lifc_len = n_ifs * sizeof (struct lifreq);
3361 	lifc.lifc_buf = malloc(lifc.lifc_len);
3362 	if (lifc.lifc_buf != NULL) {
3363 
3364 		if (ioctl(sock_fd, SIOCGLIFCONF, &lifc) == -1) {
3365 			(void) close(sock_fd);
3366 			free(lifc.lifc_buf);
3367 			return (NULL);
3368 		}
3369 
3370 		n_ifs = lifc.lifc_len / sizeof (struct lifreq);
3371 
3372 		for (i = 0; i < n_ifs; i++) {
3373 			if (ioctl(sock_fd, SIOCGLIFFLAGS, &lifc.lifc_req[i]) ==
3374 			    0 && (lifc.lifc_req[i].lifr_flags & (flags_on |
3375 			    flags_off)) != flags_on)
3376 				continue;
3377 			printed_one = dhcp_do_ipc(DHCP_STATUS |
3378 			    (af == AF_INET6 ? DHCP_V6 : 0),
3379 			    lifc.lifc_req[i].lifr_name, printed_one);
3380 		}
3381 	}
3382 	(void) close(sock_fd);
3383 	free(lifc.lifc_buf);
3384 	return (printed_one);
3385 }
3386 
3387 static void
3388 dhcp_report(char *ifname)
3389 {
3390 	boolean_t printed_one;
3391 
3392 	if (!family_selected(AF_INET) && !family_selected(AF_INET6))
3393 		return;
3394 
3395 	printed_one = B_FALSE;
3396 	if (ifname != NULL) {
3397 		if (family_selected(AF_INET)) {
3398 			printed_one = dhcp_do_ipc(DHCP_STATUS, ifname,
3399 			    printed_one);
3400 		}
3401 		if (family_selected(AF_INET6)) {
3402 			printed_one = dhcp_do_ipc(DHCP_STATUS | DHCP_V6,
3403 			    ifname, printed_one);
3404 		}
3405 		if (!printed_one) {
3406 			fail(0, "%s: %s", ifname,
3407 			    dhcp_ipc_strerror(DHCP_IPC_E_UNKIF));
3408 		}
3409 	} else {
3410 		if (family_selected(AF_INET)) {
3411 			printed_one = dhcp_walk_interfaces(IFF_DHCPRUNNING,
3412 			    0, AF_INET, printed_one);
3413 		}
3414 		if (family_selected(AF_INET6)) {
3415 			(void) dhcp_walk_interfaces(IFF_DHCPRUNNING,
3416 			    IFF_ADDRCONF, AF_INET6, printed_one);
3417 		}
3418 	}
3419 }
3420 
3421 /* --------------------- GROUP_REPORT (netstat -g) ------------------------- */
3422 
3423 static void
3424 group_report(mib_item_t *item)
3425 {
3426 	mib_item_t	*v4grp = NULL, *v4src = NULL;
3427 	mib_item_t	*v6grp = NULL, *v6src = NULL;
3428 	int		jtemp = 0;
3429 	char		ifname[LIFNAMSIZ + 1];
3430 	char		abuf[MAXHOSTNAMELEN + 1];
3431 	ip_member_t	*ipmp;
3432 	ip_grpsrc_t	*ips;
3433 	ipv6_member_t	*ipmp6;
3434 	ipv6_grpsrc_t	*ips6;
3435 	char		*ifnamep;
3436 	boolean_t	first, first_src;
3437 
3438 	/* 'for' loop 1: */
3439 	for (; item; item = item->next_item) {
3440 		if (Dflag) {
3441 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3442 			(void) printf("Group = %d, mib_id = %d, "
3443 			    "length = %d, valp = 0x%p\n",
3444 			    item->group, item->mib_id, item->length,
3445 			    item->valp);
3446 		}
3447 		if (item->group == MIB2_IP && family_selected(AF_INET)) {
3448 			switch (item->mib_id) {
3449 			case EXPER_IP_GROUP_MEMBERSHIP:
3450 				v4grp = item;
3451 				if (Dflag)
3452 					(void) printf("item is v4grp info\n");
3453 				break;
3454 			case EXPER_IP_GROUP_SOURCES:
3455 				v4src = item;
3456 				if (Dflag)
3457 					(void) printf("item is v4src info\n");
3458 				break;
3459 			default:
3460 				continue;
3461 			}
3462 			continue;
3463 		}
3464 		if (item->group == MIB2_IP6 && family_selected(AF_INET6)) {
3465 			switch (item->mib_id) {
3466 			case EXPER_IP6_GROUP_MEMBERSHIP:
3467 				v6grp = item;
3468 				if (Dflag)
3469 					(void) printf("item is v6grp info\n");
3470 				break;
3471 			case EXPER_IP6_GROUP_SOURCES:
3472 				v6src = item;
3473 				if (Dflag)
3474 					(void) printf("item is v6src info\n");
3475 				break;
3476 			default:
3477 				continue;
3478 			}
3479 		}
3480 	}
3481 
3482 	if (family_selected(AF_INET) && v4grp != NULL) {
3483 		if (Dflag)
3484 			(void) printf("%u records for ipGroupMember:\n",
3485 			    v4grp->length / sizeof (ip_member_t));
3486 
3487 		first = B_TRUE;
3488 		for (ipmp = (ip_member_t *)v4grp->valp;
3489 		    (char *)ipmp < (char *)v4grp->valp + v4grp->length;
3490 		    /* LINTED: (note 1) */
3491 		    ipmp = (ip_member_t *)((char *)ipmp + ipMemberEntrySize)) {
3492 			if (first) {
3493 				(void) puts(v4compat ?
3494 				    "Group Memberships" :
3495 				    "Group Memberships: IPv4");
3496 				(void) puts("Interface "
3497 				    "Group                RefCnt");
3498 				(void) puts("--------- "
3499 				    "-------------------- ------");
3500 				first = B_FALSE;
3501 			}
3502 
3503 			(void) printf("%-9s %-20s %6u\n",
3504 			    octetstr(&ipmp->ipGroupMemberIfIndex, 'a',
3505 			    ifname, sizeof (ifname)),
3506 			    pr_addr(ipmp->ipGroupMemberAddress,
3507 			    abuf, sizeof (abuf)),
3508 			    ipmp->ipGroupMemberRefCnt);
3509 
3510 
3511 			if (!Vflag || v4src == NULL)
3512 				continue;
3513 
3514 			if (Dflag)
3515 				(void) printf("scanning %u ipGroupSource "
3516 				    "records...\n",
3517 				    v4src->length/sizeof (ip_grpsrc_t));
3518 
3519 			first_src = B_TRUE;
3520 			for (ips = (ip_grpsrc_t *)v4src->valp;
3521 			    (char *)ips < (char *)v4src->valp + v4src->length;
3522 			    /* LINTED: (note 1) */
3523 			    ips = (ip_grpsrc_t *)((char *)ips +
3524 			    ipGroupSourceEntrySize)) {
3525 				/*
3526 				 * We assume that all source addrs for a given
3527 				 * interface/group pair are contiguous, so on
3528 				 * the first non-match after we've found at
3529 				 * least one, we bail.
3530 				 */
3531 				if ((ipmp->ipGroupMemberAddress !=
3532 				    ips->ipGroupSourceGroup) ||
3533 				    (!octetstrmatch(&ipmp->ipGroupMemberIfIndex,
3534 				    &ips->ipGroupSourceIfIndex))) {
3535 					if (first_src)
3536 						continue;
3537 					else
3538 						break;
3539 				}
3540 				if (first_src) {
3541 					(void) printf("\t%s:    %s\n",
3542 					    fmodestr(
3543 					    ipmp->ipGroupMemberFilterMode),
3544 					    pr_addr(ips->ipGroupSourceAddress,
3545 					    abuf, sizeof (abuf)));
3546 					first_src = B_FALSE;
3547 					continue;
3548 				}
3549 
3550 				(void) printf("\t            %s\n",
3551 				    pr_addr(ips->ipGroupSourceAddress, abuf,
3552 				    sizeof (abuf)));
3553 			}
3554 		}
3555 		(void) putchar('\n');
3556 	}
3557 
3558 	if (family_selected(AF_INET6) && v6grp != NULL) {
3559 		if (Dflag)
3560 			(void) printf("%u records for ipv6GroupMember:\n",
3561 			    v6grp->length / sizeof (ipv6_member_t));
3562 
3563 		first = B_TRUE;
3564 		for (ipmp6 = (ipv6_member_t *)v6grp->valp;
3565 		    (char *)ipmp6 < (char *)v6grp->valp + v6grp->length;
3566 		    /* LINTED: (note 1) */
3567 		    ipmp6 = (ipv6_member_t *)((char *)ipmp6 +
3568 			ipv6MemberEntrySize)) {
3569 			if (first) {
3570 				(void) puts("Group Memberships: "
3571 				    "IPv6");
3572 				(void) puts(" If       "
3573 				    "Group                   RefCnt");
3574 				(void) puts("----- "
3575 				    "--------------------------- ------");
3576 				first = B_FALSE;
3577 			}
3578 
3579 			ifnamep = if_indextoname(
3580 			    ipmp6->ipv6GroupMemberIfIndex, ifname);
3581 			if (ifnamep == NULL) {
3582 				(void) printf("Invalid ifindex %d\n",
3583 				    ipmp6->ipv6GroupMemberIfIndex);
3584 				continue;
3585 			}
3586 			(void) printf("%-5s %-27s %5u\n",
3587 			    ifnamep,
3588 			    pr_addr6(&ipmp6->ipv6GroupMemberAddress,
3589 			    abuf, sizeof (abuf)),
3590 			    ipmp6->ipv6GroupMemberRefCnt);
3591 
3592 			if (!Vflag || v6src == NULL)
3593 				continue;
3594 
3595 			if (Dflag)
3596 				(void) printf("scanning %u ipv6GroupSource "
3597 				    "records...\n",
3598 				    v6src->length/sizeof (ipv6_grpsrc_t));
3599 
3600 			first_src = B_TRUE;
3601 			for (ips6 = (ipv6_grpsrc_t *)v6src->valp;
3602 			    (char *)ips6 < (char *)v6src->valp + v6src->length;
3603 			    /* LINTED: (note 1) */
3604 			    ips6 = (ipv6_grpsrc_t *)((char *)ips6 +
3605 			    ipv6GroupSourceEntrySize)) {
3606 				/* same assumption as in the v4 case above */
3607 				if ((ipmp6->ipv6GroupMemberIfIndex !=
3608 				    ips6->ipv6GroupSourceIfIndex) ||
3609 				    (!IN6_ARE_ADDR_EQUAL(
3610 				    &ipmp6->ipv6GroupMemberAddress,
3611 				    &ips6->ipv6GroupSourceGroup))) {
3612 					if (first_src)
3613 						continue;
3614 					else
3615 						break;
3616 				}
3617 				if (first_src) {
3618 					(void) printf("\t%s:    %s\n",
3619 					    fmodestr(
3620 					    ipmp6->ipv6GroupMemberFilterMode),
3621 					    pr_addr6(
3622 					    &ips6->ipv6GroupSourceAddress,
3623 					    abuf, sizeof (abuf)));
3624 					first_src = B_FALSE;
3625 					continue;
3626 				}
3627 
3628 				(void) printf("\t            %s\n",
3629 				    pr_addr6(&ips6->ipv6GroupSourceAddress,
3630 				    abuf, sizeof (abuf)));
3631 			}
3632 		}
3633 		(void) putchar('\n');
3634 	}
3635 
3636 	(void) putchar('\n');
3637 	(void) fflush(stdout);
3638 }
3639 
3640 /* --------------------- ARP_REPORT (netstat -p) -------------------------- */
3641 
3642 static void
3643 arp_report(mib_item_t *item)
3644 {
3645 	int		jtemp = 0;
3646 	char		ifname[LIFNAMSIZ + 1];
3647 	char		abuf[MAXHOSTNAMELEN + 1];
3648 	char		maskbuf[STR_EXPAND * OCTET_LENGTH + 1];
3649 	char		flbuf[32];	/* ACE_F_ flags */
3650 	char		xbuf[STR_EXPAND * OCTET_LENGTH + 1];
3651 	mib2_ipNetToMediaEntry_t	*np;
3652 	int		flags;
3653 	boolean_t	first;
3654 
3655 	if (!(family_selected(AF_INET)))
3656 		return;
3657 
3658 	/* 'for' loop 1: */
3659 	for (; item; item = item->next_item) {
3660 		if (Dflag) {
3661 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3662 			(void) printf("Group = %d, mib_id = %d, "
3663 			    "length = %d, valp = 0x%p\n",
3664 			    item->group, item->mib_id, item->length,
3665 			    item->valp);
3666 		}
3667 		if (!(item->group == MIB2_IP && item->mib_id == MIB2_IP_MEDIA))
3668 			continue; /* 'for' loop 1 */
3669 
3670 		if (Dflag)
3671 			(void) printf("%u records for "
3672 			    "ipNetToMediaEntryTable:\n",
3673 			    item->length/sizeof (mib2_ipNetToMediaEntry_t));
3674 
3675 		first = B_TRUE;
3676 		/* 'for' loop 2: */
3677 		for (np = (mib2_ipNetToMediaEntry_t *)item->valp;
3678 		    (char *)np < (char *)item->valp + item->length;
3679 		    /* LINTED: (note 1) */
3680 		    np = (mib2_ipNetToMediaEntry_t *)((char *)np +
3681 		    ipNetToMediaEntrySize)) {
3682 			if (first) {
3683 				(void) puts(v4compat ?
3684 				    "Net to Media Table" :
3685 				    "Net to Media Table: IPv4");
3686 				(void) puts("Device "
3687 				    "  IP Address               Mask      "
3688 				    "Flags      Phys Addr");
3689 				(void) puts("------ "
3690 				    "-------------------- --------------- "
3691 				    "-------- ---------------");
3692 				first = B_FALSE;
3693 			}
3694 
3695 			flbuf[0] = '\0';
3696 			flags = np->ipNetToMediaInfo.ntm_flags;
3697 			/*
3698 			 * Note that not all flags are possible at the same
3699 			 * time.  Patterns: SPLAy DUo
3700 			 */
3701 			if (flags & ACE_F_PERMANENT)
3702 				(void) strcat(flbuf, "S");
3703 			if (flags & ACE_F_PUBLISH)
3704 				(void) strcat(flbuf, "P");
3705 			if (flags & ACE_F_DYING)
3706 				(void) strcat(flbuf, "D");
3707 			if (!(flags & ACE_F_RESOLVED))
3708 				(void) strcat(flbuf, "U");
3709 			if (flags & ACE_F_MAPPING)
3710 				(void) strcat(flbuf, "M");
3711 			if (flags & ACE_F_MYADDR)
3712 				(void) strcat(flbuf, "L");
3713 			if (flags & ACE_F_UNVERIFIED)
3714 				(void) strcat(flbuf, "d");
3715 			if (flags & ACE_F_AUTHORITY)
3716 				(void) strcat(flbuf, "A");
3717 			if (flags & ACE_F_OLD)
3718 				(void) strcat(flbuf, "o");
3719 			if (flags & ACE_F_DELAYED)
3720 				(void) strcat(flbuf, "y");
3721 			(void) printf("%-6s %-20s %-15s %-8s %s\n",
3722 			    octetstr(&np->ipNetToMediaIfIndex, 'a',
3723 			    ifname, sizeof (ifname)),
3724 			    pr_addr(np->ipNetToMediaNetAddress,
3725 			    abuf, sizeof (abuf)),
3726 			    octetstr(&np->ipNetToMediaInfo.ntm_mask, 'd',
3727 			    maskbuf, sizeof (maskbuf)),
3728 			    flbuf,
3729 			    octetstr(&np->ipNetToMediaPhysAddress, 'h',
3730 			    xbuf, sizeof (xbuf)));
3731 		} /* 'for' loop 2 ends */
3732 	} /* 'for' loop 1 ends */
3733 	(void) fflush(stdout);
3734 }
3735 
3736 /* --------------------- NDP_REPORT (netstat -p) -------------------------- */
3737 
3738 static void
3739 ndp_report(mib_item_t *item)
3740 {
3741 	int		jtemp = 0;
3742 	char		abuf[MAXHOSTNAMELEN + 1];
3743 	char		*state;
3744 	char		*type;
3745 	char		xbuf[STR_EXPAND * OCTET_LENGTH + 1];
3746 	mib2_ipv6NetToMediaEntry_t	*np6;
3747 	char		ifname[LIFNAMSIZ + 1];
3748 	char		*ifnamep;
3749 	boolean_t	first;
3750 
3751 	if (!(family_selected(AF_INET6)))
3752 		return;
3753 
3754 	/* 'for' loop 1: */
3755 	for (; item; item = item->next_item) {
3756 		if (Dflag) {
3757 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3758 			(void) printf("Group = %d, mib_id = %d, "
3759 			    "length = %d, valp = 0x%p\n",
3760 			    item->group, item->mib_id, item->length,
3761 			    item->valp);
3762 		}
3763 		if (!(item->group == MIB2_IP6 &&
3764 		    item->mib_id == MIB2_IP6_MEDIA))
3765 			continue; /* 'for' loop 1 */
3766 
3767 		first = B_TRUE;
3768 		/* 'for' loop 2: */
3769 		for (np6 = (mib2_ipv6NetToMediaEntry_t *)item->valp;
3770 		    (char *)np6 < (char *)item->valp + item->length;
3771 		    /* LINTED: (note 1) */
3772 		    np6 = (mib2_ipv6NetToMediaEntry_t *)((char *)np6 +
3773 		    ipv6NetToMediaEntrySize)) {
3774 			if (first) {
3775 				(void) puts("\nNet to Media Table: IPv6");
3776 				(void) puts(" If   Physical Address   "
3777 				    " Type      State      Destination/Mask");
3778 				(void) puts("----- -----------------  "
3779 				    "------- ------------ "
3780 				    "---------------------------");
3781 				first = B_FALSE;
3782 			}
3783 
3784 			ifnamep = if_indextoname(np6->ipv6NetToMediaIfIndex,
3785 			    ifname);
3786 			if (ifnamep == NULL) {
3787 				(void) printf("Invalid ifindex %d\n",
3788 				    np6->ipv6NetToMediaIfIndex);
3789 				continue; /* 'for' loop 2 */
3790 			}
3791 			switch (np6->ipv6NetToMediaState) {
3792 			case ND_INCOMPLETE:
3793 				state = "INCOMPLETE";
3794 				break;
3795 			case ND_REACHABLE:
3796 				state = "REACHABLE";
3797 				break;
3798 			case ND_STALE:
3799 				state = "STALE";
3800 				break;
3801 			case ND_DELAY:
3802 				state = "DELAY";
3803 				break;
3804 			case ND_PROBE:
3805 				state = "PROBE";
3806 				break;
3807 			case ND_UNREACHABLE:
3808 				state = "UNREACHABLE";
3809 				break;
3810 			default:
3811 				state = "UNKNOWN";
3812 			}
3813 
3814 			switch (np6->ipv6NetToMediaType) {
3815 			case 1:
3816 				type = "other";
3817 				break;
3818 			case 2:
3819 				type = "dynamic";
3820 				break;
3821 			case 3:
3822 				type = "static";
3823 				break;
3824 			case 4:
3825 				type = "local";
3826 				break;
3827 			}
3828 			(void) printf("%-5s %-17s  %-7s %-12s %-27s\n",
3829 			    ifnamep,
3830 			    octetstr(&np6->ipv6NetToMediaPhysAddress, 'h',
3831 			    xbuf, sizeof (xbuf)),
3832 			    type,
3833 			    state,
3834 			    pr_addr6(&np6->ipv6NetToMediaNetAddress,
3835 			    abuf, sizeof (abuf)));
3836 		} /* 'for' loop 2 ends */
3837 	} /* 'for' loop 1 ends */
3838 	(void) putchar('\n');
3839 	(void) fflush(stdout);
3840 }
3841 
3842 /* ------------------------- ire_report (netstat -r) ------------------------ */
3843 
3844 typedef struct sec_attr_list_s {
3845 	struct sec_attr_list_s *sal_next;
3846 	const mib2_ipAttributeEntry_t *sal_attr;
3847 } sec_attr_list_t;
3848 
3849 static boolean_t ire_report_item_v4(const mib2_ipRouteEntry_t *, boolean_t,
3850     const sec_attr_list_t *);
3851 static boolean_t ire_report_item_v6(const mib2_ipv6RouteEntry_t *, boolean_t,
3852     const sec_attr_list_t *);
3853 static const char *pr_secattr(const sec_attr_list_t *);
3854 
3855 static void
3856 ire_report(const mib_item_t *item)
3857 {
3858 	int			jtemp = 0;
3859 	boolean_t		print_hdr_once_v4 = B_TRUE;
3860 	boolean_t		print_hdr_once_v6 = B_TRUE;
3861 	mib2_ipRouteEntry_t	*rp;
3862 	mib2_ipv6RouteEntry_t	*rp6;
3863 	sec_attr_list_t		**v4_attrs, **v4a;
3864 	sec_attr_list_t		**v6_attrs, **v6a;
3865 	sec_attr_list_t		*all_attrs, *aptr;
3866 	const mib_item_t	*iptr;
3867 	int			ipv4_route_count, ipv6_route_count;
3868 	int			route_attrs_count;
3869 
3870 	/*
3871 	 * Preparation pass: the kernel returns separate entries for IP routing
3872 	 * table entries and security attributes.  We loop through the
3873 	 * attributes first and link them into lists.
3874 	 */
3875 	ipv4_route_count = ipv6_route_count = route_attrs_count = 0;
3876 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
3877 		if (iptr->group == MIB2_IP6 && iptr->mib_id == MIB2_IP6_ROUTE)
3878 			ipv6_route_count += iptr->length / ipv6RouteEntrySize;
3879 		if (iptr->group == MIB2_IP && iptr->mib_id == MIB2_IP_ROUTE)
3880 			ipv4_route_count += iptr->length / ipRouteEntrySize;
3881 		if ((iptr->group == MIB2_IP || iptr->group == MIB2_IP6) &&
3882 		    iptr->mib_id == EXPER_IP_RTATTR)
3883 			route_attrs_count += iptr->length /
3884 			    ipRouteAttributeSize;
3885 	}
3886 	v4_attrs = v6_attrs = NULL;
3887 	all_attrs = NULL;
3888 	if (family_selected(AF_INET) && ipv4_route_count > 0) {
3889 		v4_attrs = calloc(ipv4_route_count, sizeof (*v4_attrs));
3890 		if (v4_attrs == NULL) {
3891 			perror("ire_report calloc v4_attrs failed");
3892 			return;
3893 		}
3894 	}
3895 	if (family_selected(AF_INET6) && ipv6_route_count > 0) {
3896 		v6_attrs = calloc(ipv6_route_count, sizeof (*v6_attrs));
3897 		if (v6_attrs == NULL) {
3898 			perror("ire_report calloc v6_attrs failed");
3899 			goto ire_report_done;
3900 		}
3901 	}
3902 	if (route_attrs_count > 0) {
3903 		all_attrs = malloc(route_attrs_count * sizeof (*all_attrs));
3904 		if (all_attrs == NULL) {
3905 			perror("ire_report malloc all_attrs failed");
3906 			goto ire_report_done;
3907 		}
3908 	}
3909 	aptr = all_attrs;
3910 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
3911 		mib2_ipAttributeEntry_t *iae;
3912 		sec_attr_list_t **alp;
3913 
3914 		if (v4_attrs != NULL && iptr->group == MIB2_IP &&
3915 		    iptr->mib_id == EXPER_IP_RTATTR) {
3916 			alp = v4_attrs;
3917 		} else if (v6_attrs != NULL && iptr->group == MIB2_IP6 &&
3918 		    iptr->mib_id == EXPER_IP_RTATTR) {
3919 			alp = v6_attrs;
3920 		} else {
3921 			continue;
3922 		}
3923 		for (iae = iptr->valp;
3924 		    (char *)iae < (char *)iptr->valp + iptr->length;
3925 		    /* LINTED: (note 1) */
3926 		    iae = (mib2_ipAttributeEntry_t *)((char *)iae +
3927 		    ipRouteAttributeSize)) {
3928 			aptr->sal_next = alp[iae->iae_routeidx];
3929 			aptr->sal_attr = iae;
3930 			alp[iae->iae_routeidx] = aptr++;
3931 		}
3932 	}
3933 
3934 	/* 'for' loop 1: */
3935 	v4a = v4_attrs;
3936 	v6a = v6_attrs;
3937 	for (; item != NULL; item = item->next_item) {
3938 		if (Dflag) {
3939 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3940 			(void) printf("Group = %d, mib_id = %d, "
3941 			    "length = %d, valp = 0x%p\n",
3942 			    item->group, item->mib_id,
3943 			    item->length, item->valp);
3944 		}
3945 		if (!((item->group == MIB2_IP &&
3946 		    item->mib_id == MIB2_IP_ROUTE) ||
3947 		    (item->group == MIB2_IP6 &&
3948 		    item->mib_id == MIB2_IP6_ROUTE)))
3949 			continue; /* 'for' loop 1 */
3950 
3951 		if (item->group == MIB2_IP && !family_selected(AF_INET))
3952 			continue; /* 'for' loop 1 */
3953 		else if (item->group == MIB2_IP6 && !family_selected(AF_INET6))
3954 			continue; /* 'for' loop 1 */
3955 
3956 		if (Dflag) {
3957 			if (item->group == MIB2_IP) {
3958 				(void) printf("%u records for "
3959 				    "ipRouteEntryTable:\n",
3960 				    item->length/sizeof (mib2_ipRouteEntry_t));
3961 			} else {
3962 				(void) printf("%u records for "
3963 				    "ipv6RouteEntryTable:\n",
3964 				    item->length/
3965 				    sizeof (mib2_ipv6RouteEntry_t));
3966 			}
3967 		}
3968 
3969 		if (item->group == MIB2_IP) {
3970 			for (rp = (mib2_ipRouteEntry_t *)item->valp;
3971 			    (char *)rp < (char *)item->valp + item->length;
3972 			    /* LINTED: (note 1) */
3973 			    rp = (mib2_ipRouteEntry_t *)((char *)rp +
3974 			    ipRouteEntrySize)) {
3975 				aptr = v4a == NULL ? NULL : *v4a++;
3976 				print_hdr_once_v4 = ire_report_item_v4(rp,
3977 				    print_hdr_once_v4, aptr);
3978 			}
3979 		} else {
3980 			for (rp6 = (mib2_ipv6RouteEntry_t *)item->valp;
3981 			    (char *)rp6 < (char *)item->valp + item->length;
3982 			    /* LINTED: (note 1) */
3983 			    rp6 = (mib2_ipv6RouteEntry_t *)((char *)rp6 +
3984 			    ipv6RouteEntrySize)) {
3985 				aptr = v6a == NULL ? NULL : *v6a++;
3986 				print_hdr_once_v6 = ire_report_item_v6(rp6,
3987 				    print_hdr_once_v6, aptr);
3988 			}
3989 		}
3990 	} /* 'for' loop 1 ends */
3991 	(void) fflush(stdout);
3992 ire_report_done:
3993 	if (v4_attrs != NULL)
3994 		free(v4_attrs);
3995 	if (v6_attrs != NULL)
3996 		free(v6_attrs);
3997 	if (all_attrs != NULL)
3998 		free(all_attrs);
3999 }
4000 
4001 /*
4002  * Match a user-supplied device name.  We do this by string because
4003  * the MIB2 interface gives us interface name strings rather than
4004  * ifIndex numbers.  The "none" rule matches only routes with no
4005  * interface.  The "any" rule matches routes with any non-blank
4006  * interface.  A base name ("hme0") matches all aliases as well
4007  * ("hme0:1").
4008  */
4009 static boolean_t
4010 dev_name_match(const DeviceName *devnam, const char *ifname)
4011 {
4012 	int iflen;
4013 
4014 	if (ifname == NULL)
4015 		return (devnam->o_length == 0);		/* "none" */
4016 	if (*ifname == '\0')
4017 		return (devnam->o_length != 0);		/* "any" */
4018 	iflen = strlen(ifname);
4019 	/* The check for ':' here supports interface aliases. */
4020 	if (iflen > devnam->o_length ||
4021 	    (iflen < devnam->o_length && devnam->o_bytes[iflen] != ':'))
4022 		return (B_FALSE);
4023 	return (strncmp(ifname, devnam->o_bytes, iflen) == 0);
4024 }
4025 
4026 /*
4027  * Match a user-supplied IP address list.  The "any" rule matches any
4028  * non-zero address.  The "none" rule matches only the zero address.
4029  * IPv6 addresses supplied by the user are ignored.  If the user
4030  * supplies a subnet mask, then match routes that are at least that
4031  * specific (use the user's mask).  If the user supplies only an
4032  * address, then select any routes that would match (use the route's
4033  * mask).
4034  */
4035 static boolean_t
4036 v4_addr_match(IpAddress addr, IpAddress mask, const filter_t *fp)
4037 {
4038 	char **app;
4039 	char *aptr;
4040 	in_addr_t faddr, fmask;
4041 
4042 	if (fp->u.a.f_address == NULL) {
4043 		if (IN6_IS_ADDR_UNSPECIFIED(&fp->u.a.f_mask))
4044 			return (addr != INADDR_ANY);	/* "any" */
4045 		else
4046 			return (addr == INADDR_ANY);	/* "none" */
4047 	}
4048 	if (!IN6_IS_V4MASK(fp->u.a.f_mask))
4049 		return (B_FALSE);
4050 	IN6_V4MAPPED_TO_IPADDR(&fp->u.a.f_mask, fmask);
4051 	if (fmask != IP_HOST_MASK) {
4052 		if (fmask > mask)
4053 			return (B_FALSE);
4054 		mask = fmask;
4055 	}
4056 	for (app = fp->u.a.f_address->h_addr_list; (aptr = *app) != NULL; app++)
4057 		/* LINTED: (note 1) */
4058 		if (IN6_IS_ADDR_V4MAPPED((in6_addr_t *)aptr)) {
4059 			/* LINTED: (note 1) */
4060 			IN6_V4MAPPED_TO_IPADDR((in6_addr_t *)aptr, faddr);
4061 			if (((faddr ^ addr) & mask) == 0)
4062 				return (B_TRUE);
4063 		}
4064 	return (B_FALSE);
4065 }
4066 
4067 /*
4068  * Run through the filter list for an IPv4 MIB2 route entry.  If all
4069  * filters of a given type fail to match, then the route is filtered
4070  * out (not displayed).  If no filter is given or at least one filter
4071  * of each type matches, then display the route.
4072  */
4073 static boolean_t
4074 ire_filter_match_v4(const mib2_ipRouteEntry_t *rp, uint_t flag_b)
4075 {
4076 	filter_t *fp;
4077 	int idx;
4078 
4079 	/* 'for' loop 1: */
4080 	for (idx = 0; idx < NFILTERKEYS; idx++)
4081 		if ((fp = filters[idx]) != NULL) {
4082 			/* 'for' loop 2: */
4083 			for (; fp != NULL; fp = fp->f_next) {
4084 				switch (idx) {
4085 				case FK_AF:
4086 					if (fp->u.f_family != AF_INET)
4087 						continue; /* 'for' loop 2 */
4088 					break;
4089 				case FK_OUTIF:
4090 					if (!dev_name_match(&rp->ipRouteIfIndex,
4091 					    fp->u.f_ifname))
4092 						continue; /* 'for' loop 2 */
4093 					break;
4094 				case FK_DST:
4095 					if (!v4_addr_match(rp->ipRouteDest,
4096 					    rp->ipRouteMask, fp))
4097 						continue; /* 'for' loop 2 */
4098 					break;
4099 				case FK_FLAGS:
4100 					if ((flag_b & fp->u.f.f_flagset) !=
4101 					    fp->u.f.f_flagset ||
4102 					    (flag_b & fp->u.f.f_flagclear))
4103 						continue; /* 'for' loop 2 */
4104 					break;
4105 				}
4106 				break;
4107 			} /* 'for' loop 2 ends */
4108 			if (fp == NULL)
4109 				return (B_FALSE);
4110 		}
4111 	/* 'for' loop 1 ends */
4112 	return (B_TRUE);
4113 }
4114 
4115 /*
4116  * Given an IPv4 MIB2 route entry, form the list of flags for the
4117  * route.
4118  */
4119 static uint_t
4120 form_v4_route_flags(const mib2_ipRouteEntry_t *rp, char *flags)
4121 {
4122 	uint_t flag_b;
4123 
4124 	flag_b = FLF_U;
4125 	(void) strcpy(flags, "U");
4126 	if (rp->ipRouteInfo.re_ire_type == IRE_DEFAULT ||
4127 	    rp->ipRouteInfo.re_ire_type == IRE_PREFIX ||
4128 	    rp->ipRouteInfo.re_ire_type == IRE_HOST ||
4129 	    rp->ipRouteInfo.re_ire_type == IRE_HOST_REDIRECT) {
4130 		(void) strcat(flags, "G");
4131 		flag_b |= FLF_G;
4132 	}
4133 	if (rp->ipRouteMask == IP_HOST_MASK) {
4134 		(void) strcat(flags, "H");
4135 		flag_b |= FLF_H;
4136 	}
4137 	if (rp->ipRouteInfo.re_ire_type == IRE_HOST_REDIRECT) {
4138 		(void) strcat(flags, "D");
4139 		flag_b |= FLF_D;
4140 	}
4141 	if (rp->ipRouteInfo.re_ire_type == IRE_CACHE) {
4142 		/* Address resolution */
4143 		(void) strcat(flags, "A");
4144 		flag_b |= FLF_A;
4145 	}
4146 	if (rp->ipRouteInfo.re_ire_type == IRE_BROADCAST) {	/* Broadcast */
4147 		(void) strcat(flags, "B");
4148 		flag_b |= FLF_B;
4149 	}
4150 	if (rp->ipRouteInfo.re_ire_type == IRE_LOCAL) {		/* Local */
4151 		(void) strcat(flags, "L");
4152 		flag_b |= FLF_L;
4153 	}
4154 	if (rp->ipRouteInfo.re_flags & RTF_MULTIRT) {
4155 		(void) strcat(flags, "M");			/* Multiroute */
4156 		flag_b |= FLF_M;
4157 	}
4158 	if (rp->ipRouteInfo.re_flags & RTF_SETSRC) {
4159 		(void) strcat(flags, "S");			/* Setsrc */
4160 		flag_b |= FLF_S;
4161 	}
4162 	return (flag_b);
4163 }
4164 
4165 static const char ire_hdr_v4[] =
4166 "\n%s Table: IPv4\n";
4167 static const char ire_hdr_v4_compat[] =
4168 "\n%s Table:\n";
4169 static const char ire_hdr_v4_verbose[] =
4170 "  Destination             Mask           Gateway          Device Mxfrg "
4171 "Rtt   Ref Flg  Out  In/Fwd %s\n"
4172 "-------------------- --------------- -------------------- ------ ----- "
4173 "----- --- --- ----- ------ %s\n";
4174 
4175 static const char ire_hdr_v4_normal[] =
4176 "  Destination           Gateway           Flags  Ref     Use     Interface"
4177 " %s\n-------------------- -------------------- ----- ----- ---------- "
4178 "--------- %s\n";
4179 
4180 static boolean_t
4181 ire_report_item_v4(const mib2_ipRouteEntry_t *rp, boolean_t first,
4182     const sec_attr_list_t *attrs)
4183 {
4184 	char			dstbuf[MAXHOSTNAMELEN + 1];
4185 	char			maskbuf[MAXHOSTNAMELEN + 1];
4186 	char			gwbuf[MAXHOSTNAMELEN + 1];
4187 	char			ifname[LIFNAMSIZ + 1];
4188 	char			flags[10];	/* RTF_ flags */
4189 	uint_t			flag_b;
4190 
4191 	if (!(Aflag || (rp->ipRouteInfo.re_ire_type != IRE_CACHE &&
4192 	    rp->ipRouteInfo.re_ire_type != IRE_BROADCAST &&
4193 	    rp->ipRouteInfo.re_ire_type != IRE_LOCAL))) {
4194 		return (first);
4195 	}
4196 
4197 	flag_b = form_v4_route_flags(rp, flags);
4198 
4199 	if (!ire_filter_match_v4(rp, flag_b))
4200 		return (first);
4201 
4202 	if (first) {
4203 		(void) printf(v4compat ? ire_hdr_v4_compat : ire_hdr_v4,
4204 		    Vflag ? "IRE" : "Routing");
4205 		(void) printf(Vflag ? ire_hdr_v4_verbose : ire_hdr_v4_normal,
4206 		    RSECflag ? "  Gateway security attributes  " : "",
4207 		    RSECflag ? "-------------------------------" : "");
4208 		first = B_FALSE;
4209 	}
4210 
4211 	if (flag_b & FLF_H) {
4212 		(void) pr_addr(rp->ipRouteDest, dstbuf, sizeof (dstbuf));
4213 	} else {
4214 		(void) pr_net(rp->ipRouteDest, rp->ipRouteMask,
4215 		    dstbuf, sizeof (dstbuf));
4216 	}
4217 	if (Vflag) {
4218 		(void) printf("%-20s %-15s %-20s %-6s %5u%c %4u %3u "
4219 		    "%-4s%6u %6u %s\n",
4220 		    dstbuf,
4221 		    pr_mask(rp->ipRouteMask, maskbuf, sizeof (maskbuf)),
4222 		    pr_addrnz(rp->ipRouteNextHop, gwbuf, sizeof (gwbuf)),
4223 		    octetstr(&rp->ipRouteIfIndex, 'a', ifname, sizeof (ifname)),
4224 		    rp->ipRouteInfo.re_max_frag,
4225 		    rp->ipRouteInfo.re_frag_flag ? '*' : ' ',
4226 		    rp->ipRouteInfo.re_rtt,
4227 		    rp->ipRouteInfo.re_ref,
4228 		    flags,
4229 		    rp->ipRouteInfo.re_obpkt,
4230 		    rp->ipRouteInfo.re_ibpkt,
4231 		    pr_secattr(attrs));
4232 	} else {
4233 		(void) printf("%-20s %-20s %-5s  %4u %10u %-9s %s\n",
4234 		    dstbuf,
4235 		    pr_addrnz(rp->ipRouteNextHop, gwbuf, sizeof (gwbuf)),
4236 		    flags,
4237 		    rp->ipRouteInfo.re_ref,
4238 		    rp->ipRouteInfo.re_obpkt + rp->ipRouteInfo.re_ibpkt,
4239 		    octetstr(&rp->ipRouteIfIndex, 'a',
4240 		    ifname, sizeof (ifname)),
4241 		    pr_secattr(attrs));
4242 	}
4243 	return (first);
4244 }
4245 
4246 /*
4247  * Match a user-supplied IP address list against an IPv6 route entry.
4248  * If the user specified "any," then any non-zero address matches.  If
4249  * the user specified "none," then only the zero address matches.  If
4250  * the user specified a subnet mask length, then use that in matching
4251  * routes (select routes that are at least as specific).  If the user
4252  * specified only an address, then use the route's mask (select routes
4253  * that would match that address).  IPv4 addresses are ignored.
4254  */
4255 static boolean_t
4256 v6_addr_match(const Ip6Address *addr, int masklen, const filter_t *fp)
4257 {
4258 	const uint8_t *ucp;
4259 	int fmasklen;
4260 	int i;
4261 	char **app;
4262 	char *aptr;
4263 
4264 	if (fp->u.a.f_address == NULL) {
4265 		if (IN6_IS_ADDR_UNSPECIFIED(&fp->u.a.f_mask))	/* any */
4266 			return (!IN6_IS_ADDR_UNSPECIFIED(addr));
4267 		return (IN6_IS_ADDR_UNSPECIFIED(addr));		/* "none" */
4268 	}
4269 	fmasklen = 0;
4270 	/* 'for' loop 1a: */
4271 	for (ucp = fp->u.a.f_mask.s6_addr;
4272 	    ucp < fp->u.a.f_mask.s6_addr + sizeof (fp->u.a.f_mask.s6_addr);
4273 	    ucp++) {
4274 		if (*ucp != 0xff) {
4275 			if (*ucp != 0)
4276 				fmasklen += 9 - ffs(*ucp);
4277 			break; /* 'for' loop 1a */
4278 		}
4279 		fmasklen += 8;
4280 	} /* 'for' loop 1a ends */
4281 	if (fmasklen != IPV6_ABITS) {
4282 		if (fmasklen > masklen)
4283 			return (B_FALSE);
4284 		masklen = fmasklen;
4285 	}
4286 	/* 'for' loop 1b: */
4287 	for (app = fp->u.a.f_address->h_addr_list; (aptr = *app) != NULL;
4288 	    app++) {
4289 		/* LINTED: (note 1) */
4290 		if (IN6_IS_ADDR_V4MAPPED((in6_addr_t *)aptr))
4291 			continue; /* 'for' loop 1b */
4292 		ucp = addr->s6_addr;
4293 		for (i = masklen; i >= 8; i -= 8)
4294 			if (*ucp++ != *aptr++)
4295 				break; /* 'for' loop 1b */
4296 		if (i == 0 ||
4297 		    (i < 8 && ((*ucp ^ *aptr) & ~(0xff >> i)) == 0))
4298 			return (B_TRUE);
4299 	} /* 'for' loop 1b ends */
4300 	return (B_FALSE);
4301 }
4302 
4303 /*
4304  * Run through the filter list for an IPv6 MIB2 IRE.  For a given
4305  * type, if there's at least one filter and all filters of that type
4306  * fail to match, then the route doesn't match and isn't displayed.
4307  * If at least one matches, or none are specified, for each of the
4308  * types, then the route is selected and displayed.
4309  */
4310 static boolean_t
4311 ire_filter_match_v6(const mib2_ipv6RouteEntry_t *rp6, uint_t flag_b)
4312 {
4313 	filter_t *fp;
4314 	int idx;
4315 
4316 	/* 'for' loop 1: */
4317 	for (idx = 0; idx < NFILTERKEYS; idx++)
4318 		if ((fp = filters[idx]) != NULL) {
4319 			/* 'for' loop 2: */
4320 			for (; fp != NULL; fp = fp->f_next) {
4321 				switch (idx) {
4322 				case FK_AF:
4323 					if (fp->u.f_family != AF_INET6)
4324 						/* 'for' loop 2 */
4325 						continue;
4326 					break;
4327 				case FK_OUTIF:
4328 					if (!dev_name_match(&rp6->
4329 					    ipv6RouteIfIndex, fp->u.f_ifname))
4330 						/* 'for' loop 2 */
4331 						continue;
4332 					break;
4333 				case FK_DST:
4334 					if (!v6_addr_match(&rp6->ipv6RouteDest,
4335 					    rp6->ipv6RoutePfxLength, fp))
4336 						/* 'for' loop 2 */
4337 						continue;
4338 					break;
4339 				case FK_FLAGS:
4340 					if ((flag_b & fp->u.f.f_flagset) !=
4341 					    fp->u.f.f_flagset ||
4342 					    (flag_b & fp->u.f.f_flagclear))
4343 						/* 'for' loop 2 */
4344 						continue;
4345 					break;
4346 				}
4347 				break;
4348 			} /* 'for' loop 2 ends */
4349 			if (fp == NULL)
4350 				return (B_FALSE);
4351 		}
4352 	/* 'for' loop 1 ends */
4353 	return (B_TRUE);
4354 }
4355 
4356 static const char ire_hdr_v6[] =
4357 "\n%s Table: IPv6\n";
4358 static const char ire_hdr_v6_verbose[] =
4359 "  Destination/Mask            Gateway                    If    PMTU   Rtt  "
4360 "Ref Flags  Out   In/Fwd %s\n"
4361 "--------------------------- --------------------------- ----- ------ ----- "
4362 "--- ----- ------ ------ %s\n";
4363 static const char ire_hdr_v6_normal[] =
4364 "  Destination/Mask            Gateway                   Flags Ref   Use  "
4365 "  If   %s\n"
4366 "--------------------------- --------------------------- ----- --- ------- "
4367 "----- %s\n";
4368 
4369 static boolean_t
4370 ire_report_item_v6(const mib2_ipv6RouteEntry_t *rp6, boolean_t first,
4371     const sec_attr_list_t *attrs)
4372 {
4373 	char			dstbuf[MAXHOSTNAMELEN + 1];
4374 	char			gwbuf[MAXHOSTNAMELEN + 1];
4375 	char			ifname[LIFNAMSIZ + 1];
4376 	char			flags[10];	/* RTF_ flags */
4377 	uint_t			flag_b;
4378 
4379 	if (!(Aflag || (rp6->ipv6RouteInfo.re_ire_type != IRE_CACHE &&
4380 	    rp6->ipv6RouteInfo.re_ire_type != IRE_LOCAL))) {
4381 		return (first);
4382 	}
4383 
4384 	flag_b = FLF_U;
4385 	(void) strcpy(flags, "U");
4386 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_DEFAULT ||
4387 	    rp6->ipv6RouteInfo.re_ire_type == IRE_PREFIX ||
4388 	    rp6->ipv6RouteInfo.re_ire_type == IRE_HOST ||
4389 	    rp6->ipv6RouteInfo.re_ire_type == IRE_HOST_REDIRECT) {
4390 		(void) strcat(flags, "G");
4391 		flag_b |= FLF_G;
4392 	}
4393 
4394 	if (rp6->ipv6RoutePfxLength == IPV6_ABITS) {
4395 		(void) strcat(flags, "H");
4396 		flag_b |= FLF_H;
4397 	}
4398 
4399 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_HOST_REDIRECT) {
4400 		(void) strcat(flags, "D");
4401 		flag_b |= FLF_D;
4402 	}
4403 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_CACHE) {
4404 		/* Address resolution */
4405 		(void) strcat(flags, "A");
4406 		flag_b |= FLF_A;
4407 	}
4408 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_LOCAL) {	/* Local */
4409 		(void) strcat(flags, "L");
4410 		flag_b |= FLF_L;
4411 	}
4412 	if (rp6->ipv6RouteInfo.re_flags & RTF_MULTIRT) {
4413 		(void) strcat(flags, "M");			/* Multiroute */
4414 		flag_b |= FLF_M;
4415 	}
4416 	if (rp6->ipv6RouteInfo.re_flags & RTF_SETSRC) {
4417 		(void) strcat(flags, "S");			/* Setsrc */
4418 		flag_b |= FLF_S;
4419 	}
4420 
4421 	if (!ire_filter_match_v6(rp6, flag_b))
4422 		return (first);
4423 
4424 	if (first) {
4425 		(void) printf(ire_hdr_v6, Vflag ? "IRE" : "Routing");
4426 		(void) printf(Vflag ? ire_hdr_v6_verbose : ire_hdr_v6_normal,
4427 		    RSECflag ? "  Gateway security attributes  " : "",
4428 		    RSECflag ? "-------------------------------" : "");
4429 		first = B_FALSE;
4430 	}
4431 
4432 	if (Vflag) {
4433 		(void) printf("%-27s %-27s %-5s %5u%c %5u %3u "
4434 		    "%-5s %6u %6u %s\n",
4435 		    pr_prefix6(&rp6->ipv6RouteDest,
4436 			rp6->ipv6RoutePfxLength, dstbuf, sizeof (dstbuf)),
4437 		    IN6_IS_ADDR_UNSPECIFIED(&rp6->ipv6RouteNextHop) ?
4438 		    "    --" :
4439 		    pr_addr6(&rp6->ipv6RouteNextHop, gwbuf, sizeof (gwbuf)),
4440 		    octetstr(&rp6->ipv6RouteIfIndex, 'a',
4441 		    ifname, sizeof (ifname)),
4442 		    rp6->ipv6RouteInfo.re_max_frag,
4443 		    rp6->ipv6RouteInfo.re_frag_flag ? '*' : ' ',
4444 		    rp6->ipv6RouteInfo.re_rtt,
4445 		    rp6->ipv6RouteInfo.re_ref,
4446 		    flags,
4447 		    rp6->ipv6RouteInfo.re_obpkt,
4448 		    rp6->ipv6RouteInfo.re_ibpkt,
4449 		    pr_secattr(attrs));
4450 	} else {
4451 		(void) printf("%-27s %-27s %-5s %3u %7u %-5s %s\n",
4452 		    pr_prefix6(&rp6->ipv6RouteDest,
4453 			rp6->ipv6RoutePfxLength, dstbuf, sizeof (dstbuf)),
4454 		    IN6_IS_ADDR_UNSPECIFIED(&rp6->ipv6RouteNextHop) ?
4455 		    "    --" :
4456 		    pr_addr6(&rp6->ipv6RouteNextHop, gwbuf, sizeof (gwbuf)),
4457 		    flags,
4458 		    rp6->ipv6RouteInfo.re_ref,
4459 		    rp6->ipv6RouteInfo.re_obpkt + rp6->ipv6RouteInfo.re_ibpkt,
4460 		    octetstr(&rp6->ipv6RouteIfIndex, 'a',
4461 		    ifname, sizeof (ifname)),
4462 		    pr_secattr(attrs));
4463 	}
4464 	return (first);
4465 }
4466 
4467 /*
4468  * Common attribute-gathering routine for all transports.
4469  */
4470 static mib2_transportMLPEntry_t **
4471 gather_attrs(const mib_item_t *item, int group, int mib_id, int esize)
4472 {
4473 	int transport_count = 0;
4474 	const mib_item_t *iptr;
4475 	mib2_transportMLPEntry_t **attrs, *tme;
4476 
4477 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
4478 		if (iptr->group == group && iptr->mib_id == mib_id)
4479 			transport_count += iptr->length / esize;
4480 	}
4481 	if (transport_count <= 0)
4482 		return (NULL);
4483 	attrs = calloc(transport_count, sizeof (*attrs));
4484 	if (attrs == NULL) {
4485 		perror("gather_attrs calloc failed");
4486 		return (NULL);
4487 	}
4488 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
4489 		if (iptr->group == group && iptr->mib_id == EXPER_XPORT_MLP) {
4490 			for (tme = iptr->valp;
4491 			    (char *)tme < (char *)iptr->valp + iptr->length;
4492 			    /* LINTED: (note 1) */
4493 			    tme = (mib2_transportMLPEntry_t *)((char *)tme +
4494 			    transportMLPSize)) {
4495 				attrs[tme->tme_connidx] = tme;
4496 			}
4497 		}
4498 	}
4499 	return (attrs);
4500 }
4501 
4502 static void
4503 print_transport_label(const mib2_transportMLPEntry_t *attr)
4504 {
4505 	if (!RSECflag || attr == NULL)
4506 		return;
4507 
4508 	if (bisinvalid(&attr->tme_label))
4509 		(void) printf("   INVALID\n");
4510 	else
4511 		(void) printf("   %s\n", sl_to_str(&attr->tme_label));
4512 }
4513 
4514 /* ------------------------------ TCP_REPORT------------------------------- */
4515 
4516 static const char tcp_hdr_v4[] =
4517 "\nTCP: IPv4\n";
4518 static const char tcp_hdr_v4_compat[] =
4519 "\nTCP\n";
4520 static const char tcp_hdr_v4_verbose[] =
4521 "Local/Remote Address Swind  Snext     Suna   Rwind  Rnext     Rack   "
4522 " Rto   Mss     State\n"
4523 "-------------------- ----- -------- -------- ----- -------- -------- "
4524 "----- ----- -----------\n";
4525 static const char tcp_hdr_v4_normal[] =
4526 "   Local Address        Remote Address    Swind Send-Q Rwind Recv-Q "
4527 "   State\n"
4528 "-------------------- -------------------- ----- ------ ----- ------ "
4529 "-----------\n";
4530 
4531 static const char tcp_hdr_v6[] =
4532 "\nTCP: IPv6\n";
4533 static const char tcp_hdr_v6_verbose[] =
4534 "Local/Remote Address              Swind  Snext     Suna   Rwind  Rnext   "
4535 "  Rack    Rto   Mss    State      If\n"
4536 "--------------------------------- ----- -------- -------- ----- -------- "
4537 "-------- ----- ----- ----------- -----\n";
4538 static const char tcp_hdr_v6_normal[] =
4539 "   Local Address                     Remote Address                 "
4540 "Swind Send-Q Rwind Recv-Q   State      If\n"
4541 "--------------------------------- --------------------------------- "
4542 "----- ------ ----- ------ ----------- -----\n";
4543 
4544 static boolean_t tcp_report_item_v4(const mib2_tcpConnEntry_t *,
4545     boolean_t first, const mib2_transportMLPEntry_t *);
4546 static boolean_t tcp_report_item_v6(const mib2_tcp6ConnEntry_t *,
4547     boolean_t first, const mib2_transportMLPEntry_t *);
4548 
4549 static void
4550 tcp_report(const mib_item_t *item)
4551 {
4552 	int			jtemp = 0;
4553 	boolean_t		print_hdr_once_v4 = B_TRUE;
4554 	boolean_t		print_hdr_once_v6 = B_TRUE;
4555 	mib2_tcpConnEntry_t	*tp;
4556 	mib2_tcp6ConnEntry_t	*tp6;
4557 	mib2_transportMLPEntry_t **v4_attrs, **v6_attrs;
4558 	mib2_transportMLPEntry_t **v4a, **v6a;
4559 	mib2_transportMLPEntry_t *aptr;
4560 
4561 	if (!protocol_selected(IPPROTO_TCP))
4562 		return;
4563 
4564 	/*
4565 	 * Preparation pass: the kernel returns separate entries for TCP
4566 	 * connection table entries and Multilevel Port attributes.  We loop
4567 	 * through the attributes first and set up an array for each address
4568 	 * family.
4569 	 */
4570 	v4_attrs = family_selected(AF_INET) && RSECflag ?
4571 	    gather_attrs(item, MIB2_TCP, MIB2_TCP_CONN, tcpConnEntrySize) :
4572 	    NULL;
4573 	v6_attrs = family_selected(AF_INET6) && RSECflag ?
4574 	    gather_attrs(item, MIB2_TCP6, MIB2_TCP6_CONN, tcp6ConnEntrySize) :
4575 	    NULL;
4576 
4577 	/* 'for' loop 1: */
4578 	v4a = v4_attrs;
4579 	v6a = v6_attrs;
4580 	for (; item != NULL; item = item->next_item) {
4581 		if (Dflag) {
4582 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
4583 			(void) printf("Group = %d, mib_id = %d, "
4584 			    "length = %d, valp = 0x%p\n",
4585 			    item->group, item->mib_id,
4586 			    item->length, item->valp);
4587 		}
4588 
4589 		if (!((item->group == MIB2_TCP &&
4590 		    item->mib_id == MIB2_TCP_CONN) ||
4591 		    (item->group == MIB2_TCP6 &&
4592 		    item->mib_id == MIB2_TCP6_CONN)))
4593 			continue; /* 'for' loop 1 */
4594 
4595 		if (item->group == MIB2_TCP && !family_selected(AF_INET))
4596 			continue; /* 'for' loop 1 */
4597 		else if (item->group == MIB2_TCP6 && !family_selected(AF_INET6))
4598 			continue; /* 'for' loop 1 */
4599 
4600 		if (item->group == MIB2_TCP) {
4601 			for (tp = (mib2_tcpConnEntry_t *)item->valp;
4602 			    (char *)tp < (char *)item->valp + item->length;
4603 			    /* LINTED: (note 1) */
4604 			    tp = (mib2_tcpConnEntry_t *)((char *)tp +
4605 			    tcpConnEntrySize)) {
4606 				aptr = v4a == NULL ? NULL : *v4a++;
4607 				print_hdr_once_v4 = tcp_report_item_v4(tp,
4608 				    print_hdr_once_v4, aptr);
4609 			}
4610 		} else {
4611 			for (tp6 = (mib2_tcp6ConnEntry_t *)item->valp;
4612 			    (char *)tp6 < (char *)item->valp + item->length;
4613 			    /* LINTED: (note 1) */
4614 			    tp6 = (mib2_tcp6ConnEntry_t *)((char *)tp6 +
4615 			    tcp6ConnEntrySize)) {
4616 				aptr = v6a == NULL ? NULL : *v6a++;
4617 				print_hdr_once_v6 = tcp_report_item_v6(tp6,
4618 				    print_hdr_once_v6, aptr);
4619 			}
4620 		}
4621 	} /* 'for' loop 1 ends */
4622 	(void) fflush(stdout);
4623 
4624 	if (v4_attrs != NULL)
4625 		free(v4_attrs);
4626 	if (v6_attrs != NULL)
4627 		free(v6_attrs);
4628 }
4629 
4630 static boolean_t
4631 tcp_report_item_v4(const mib2_tcpConnEntry_t *tp, boolean_t first,
4632     const mib2_transportMLPEntry_t *attr)
4633 {
4634 	/*
4635 	 * lname and fname below are for the hostname as well as the portname
4636 	 * There is no limit on portname length so we assume MAXHOSTNAMELEN
4637 	 * as the limit
4638 	 */
4639 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4640 	char	fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4641 
4642 	if (!(Aflag || tp->tcpConnEntryInfo.ce_state >= TCPS_ESTABLISHED))
4643 		return (first); /* Nothing to print */
4644 
4645 	if (first) {
4646 		(void) printf(v4compat ? tcp_hdr_v4_compat : tcp_hdr_v4);
4647 		(void) printf(Vflag ? tcp_hdr_v4_verbose : tcp_hdr_v4_normal);
4648 	}
4649 
4650 	if (Vflag) {
4651 		(void) printf("%-20s\n%-20s %5u %08x %08x %5u %08x %08x "
4652 		    "%5u %5u %s\n",
4653 		    pr_ap(tp->tcpConnLocalAddress,
4654 			tp->tcpConnLocalPort, "tcp", lname, sizeof (lname)),
4655 		    pr_ap(tp->tcpConnRemAddress,
4656 			tp->tcpConnRemPort, "tcp", fname, sizeof (fname)),
4657 		    tp->tcpConnEntryInfo.ce_swnd,
4658 		    tp->tcpConnEntryInfo.ce_snxt,
4659 		    tp->tcpConnEntryInfo.ce_suna,
4660 		    tp->tcpConnEntryInfo.ce_rwnd,
4661 		    tp->tcpConnEntryInfo.ce_rnxt,
4662 		    tp->tcpConnEntryInfo.ce_rack,
4663 		    tp->tcpConnEntryInfo.ce_rto,
4664 		    tp->tcpConnEntryInfo.ce_mss,
4665 		    mitcp_state(tp->tcpConnEntryInfo.ce_state, attr));
4666 	} else {
4667 		int sq = (int)tp->tcpConnEntryInfo.ce_snxt -
4668 		    (int)tp->tcpConnEntryInfo.ce_suna - 1;
4669 		int rq = (int)tp->tcpConnEntryInfo.ce_rnxt -
4670 		    (int)tp->tcpConnEntryInfo.ce_rack;
4671 
4672 		(void) printf("%-20s %-20s %5u %6d %5u %6d %s\n",
4673 		    pr_ap(tp->tcpConnLocalAddress,
4674 			tp->tcpConnLocalPort, "tcp", lname, sizeof (lname)),
4675 		    pr_ap(tp->tcpConnRemAddress,
4676 			tp->tcpConnRemPort, "tcp", fname, sizeof (fname)),
4677 		    tp->tcpConnEntryInfo.ce_swnd,
4678 		    (sq >= 0) ? sq : 0,
4679 		    tp->tcpConnEntryInfo.ce_rwnd,
4680 		    (rq >= 0) ? rq : 0,
4681 		    mitcp_state(tp->tcpConnEntryInfo.ce_state, attr));
4682 	}
4683 
4684 	print_transport_label(attr);
4685 
4686 	return (B_FALSE);
4687 }
4688 
4689 static boolean_t
4690 tcp_report_item_v6(const mib2_tcp6ConnEntry_t *tp6, boolean_t first,
4691     const mib2_transportMLPEntry_t *attr)
4692 {
4693 	/*
4694 	 * lname and fname below are for the hostname as well as the portname
4695 	 * There is no limit on portname length so we assume MAXHOSTNAMELEN
4696 	 * as the limit
4697 	 */
4698 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4699 	char	fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4700 	char	ifname[LIFNAMSIZ + 1];
4701 	char	*ifnamep;
4702 
4703 	if (!(Aflag || tp6->tcp6ConnEntryInfo.ce_state >= TCPS_ESTABLISHED))
4704 		return (first); /* Nothing to print */
4705 
4706 	if (first) {
4707 		(void) printf(tcp_hdr_v6);
4708 		(void) printf(Vflag ? tcp_hdr_v6_verbose : tcp_hdr_v6_normal);
4709 	}
4710 
4711 	ifnamep = (tp6->tcp6ConnIfIndex != 0) ?
4712 	    if_indextoname(tp6->tcp6ConnIfIndex, ifname) : NULL;
4713 	if (ifnamep == NULL)
4714 		ifnamep = "";
4715 
4716 	if (Vflag) {
4717 		(void) printf("%-33s\n%-33s %5u %08x %08x %5u %08x %08x "
4718 		    "%5u %5u %-11s %s\n",
4719 		    pr_ap6(&tp6->tcp6ConnLocalAddress,
4720 			tp6->tcp6ConnLocalPort, "tcp", lname, sizeof (lname)),
4721 		    pr_ap6(&tp6->tcp6ConnRemAddress,
4722 			tp6->tcp6ConnRemPort, "tcp", fname, sizeof (fname)),
4723 		    tp6->tcp6ConnEntryInfo.ce_swnd,
4724 		    tp6->tcp6ConnEntryInfo.ce_snxt,
4725 		    tp6->tcp6ConnEntryInfo.ce_suna,
4726 		    tp6->tcp6ConnEntryInfo.ce_rwnd,
4727 		    tp6->tcp6ConnEntryInfo.ce_rnxt,
4728 		    tp6->tcp6ConnEntryInfo.ce_rack,
4729 		    tp6->tcp6ConnEntryInfo.ce_rto,
4730 		    tp6->tcp6ConnEntryInfo.ce_mss,
4731 		    mitcp_state(tp6->tcp6ConnEntryInfo.ce_state, attr),
4732 		    ifnamep);
4733 	} else {
4734 		int sq = (int)tp6->tcp6ConnEntryInfo.ce_snxt -
4735 		    (int)tp6->tcp6ConnEntryInfo.ce_suna - 1;
4736 		int rq = (int)tp6->tcp6ConnEntryInfo.ce_rnxt -
4737 		    (int)tp6->tcp6ConnEntryInfo.ce_rack;
4738 
4739 		(void) printf("%-33s %-33s %5u %6d %5u %6d %-11s %s\n",
4740 		    pr_ap6(&tp6->tcp6ConnLocalAddress,
4741 			tp6->tcp6ConnLocalPort, "tcp", lname, sizeof (lname)),
4742 		    pr_ap6(&tp6->tcp6ConnRemAddress,
4743 			tp6->tcp6ConnRemPort, "tcp", fname, sizeof (fname)),
4744 		    tp6->tcp6ConnEntryInfo.ce_swnd,
4745 		    (sq >= 0) ? sq : 0,
4746 		    tp6->tcp6ConnEntryInfo.ce_rwnd,
4747 		    (rq >= 0) ? rq : 0,
4748 		    mitcp_state(tp6->tcp6ConnEntryInfo.ce_state, attr),
4749 		    ifnamep);
4750 	}
4751 
4752 	print_transport_label(attr);
4753 
4754 	return (B_FALSE);
4755 }
4756 
4757 /* ------------------------------- UDP_REPORT------------------------------- */
4758 
4759 static boolean_t udp_report_item_v4(const mib2_udpEntry_t *ude,
4760     boolean_t first, const mib2_transportMLPEntry_t *attr);
4761 static boolean_t udp_report_item_v6(const mib2_udp6Entry_t *ude6,
4762     boolean_t first, const mib2_transportMLPEntry_t *attr);
4763 
4764 static const char udp_hdr_v4[] =
4765 "   Local Address        Remote Address      State\n"
4766 "-------------------- -------------------- ----------\n";
4767 
4768 static const char udp_hdr_v6[] =
4769 "   Local Address                     Remote Address                 "
4770 "  State      If\n"
4771 "--------------------------------- --------------------------------- "
4772 "---------- -----\n";
4773 
4774 static void
4775 udp_report(const mib_item_t *item)
4776 {
4777 	int			jtemp = 0;
4778 	boolean_t		print_hdr_once_v4 = B_TRUE;
4779 	boolean_t		print_hdr_once_v6 = B_TRUE;
4780 	mib2_udpEntry_t		*ude;
4781 	mib2_udp6Entry_t	*ude6;
4782 	mib2_transportMLPEntry_t **v4_attrs, **v6_attrs;
4783 	mib2_transportMLPEntry_t **v4a, **v6a;
4784 	mib2_transportMLPEntry_t *aptr;
4785 
4786 	if (!protocol_selected(IPPROTO_UDP))
4787 		return;
4788 
4789 	/*
4790 	 * Preparation pass: the kernel returns separate entries for UDP
4791 	 * connection table entries and Multilevel Port attributes.  We loop
4792 	 * through the attributes first and set up an array for each address
4793 	 * family.
4794 	 */
4795 	v4_attrs = family_selected(AF_INET) && RSECflag ?
4796 	    gather_attrs(item, MIB2_UDP, MIB2_UDP_ENTRY, udpEntrySize) : NULL;
4797 	v6_attrs = family_selected(AF_INET6) && RSECflag ?
4798 	    gather_attrs(item, MIB2_UDP6, MIB2_UDP6_ENTRY, udp6EntrySize) :
4799 	    NULL;
4800 
4801 	v4a = v4_attrs;
4802 	v6a = v6_attrs;
4803 	/* 'for' loop 1: */
4804 	for (; item; item = item->next_item) {
4805 		if (Dflag) {
4806 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
4807 			(void) printf("Group = %d, mib_id = %d, "
4808 			    "length = %d, valp = 0x%p\n",
4809 			    item->group, item->mib_id,
4810 			    item->length, item->valp);
4811 		}
4812 		if (!((item->group == MIB2_UDP &&
4813 		    item->mib_id == MIB2_UDP_ENTRY) ||
4814 		    (item->group == MIB2_UDP6 &&
4815 		    item->mib_id == MIB2_UDP6_ENTRY)))
4816 			continue; /* 'for' loop 1 */
4817 
4818 		if (item->group == MIB2_UDP && !family_selected(AF_INET))
4819 			continue; /* 'for' loop 1 */
4820 		else if (item->group == MIB2_UDP6 && !family_selected(AF_INET6))
4821 			continue; /* 'for' loop 1 */
4822 
4823 		/*	xxx.xxx.xxx.xxx,pppp  sss... */
4824 		if (item->group == MIB2_UDP) {
4825 			for (ude = (mib2_udpEntry_t *)item->valp;
4826 			    (char *)ude < (char *)item->valp + item->length;
4827 			    /* LINTED: (note 1) */
4828 			    ude = (mib2_udpEntry_t *)((char *)ude +
4829 			    udpEntrySize)) {
4830 				aptr = v4a == NULL ? NULL : *v4a++;
4831 				print_hdr_once_v4 = udp_report_item_v4(ude,
4832 				    print_hdr_once_v4, aptr);
4833 			}
4834 		} else {
4835 			for (ude6 = (mib2_udp6Entry_t *)item->valp;
4836 			    (char *)ude6 < (char *)item->valp + item->length;
4837 			    /* LINTED: (note 1) */
4838 			    ude6 = (mib2_udp6Entry_t *)((char *)ude6 +
4839 			    udp6EntrySize)) {
4840 				aptr = v6a == NULL ? NULL : *v6a++;
4841 				print_hdr_once_v6 = udp_report_item_v6(ude6,
4842 				    print_hdr_once_v6, aptr);
4843 			}
4844 		}
4845 	} /* 'for' loop 1 ends */
4846 	(void) fflush(stdout);
4847 
4848 	if (v4_attrs != NULL)
4849 		free(v4_attrs);
4850 	if (v6_attrs != NULL)
4851 		free(v6_attrs);
4852 }
4853 
4854 static boolean_t
4855 udp_report_item_v4(const mib2_udpEntry_t *ude, boolean_t first,
4856     const mib2_transportMLPEntry_t *attr)
4857 {
4858 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4859 			/* hostname + portname */
4860 
4861 	if (!(Aflag || ude->udpEntryInfo.ue_state >= MIB2_UDP_connected))
4862 		return (first); /* Nothing to print */
4863 
4864 	if (first) {
4865 		(void) printf(v4compat ? "\nUDP\n" : "\nUDP: IPv4\n");
4866 		(void) printf(udp_hdr_v4);
4867 		first = B_FALSE;
4868 	}
4869 
4870 	(void) printf("%-20s ",
4871 	    pr_ap(ude->udpLocalAddress, ude->udpLocalPort, "udp",
4872 	    lname, sizeof (lname)));
4873 	(void) printf("%-20s %s\n",
4874 	    ude->udpEntryInfo.ue_state == MIB2_UDP_connected ?
4875 	    pr_ap(ude->udpEntryInfo.ue_RemoteAddress,
4876 	    ude->udpEntryInfo.ue_RemotePort, "udp", lname, sizeof (lname)) :
4877 	    "",
4878 	    miudp_state(ude->udpEntryInfo.ue_state, attr));
4879 
4880 	/*
4881 	 * UDP sockets don't have remote attributes, so there's no need to
4882 	 * print them here.
4883 	 */
4884 
4885 	return (first);
4886 }
4887 
4888 static boolean_t
4889 udp_report_item_v6(const mib2_udp6Entry_t *ude6, boolean_t first,
4890     const mib2_transportMLPEntry_t *attr)
4891 {
4892 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4893 			/* hostname + portname */
4894 	char	ifname[LIFNAMSIZ + 1];
4895 	const char *ifnamep;
4896 
4897 	if (!(Aflag || ude6->udp6EntryInfo.ue_state >= MIB2_UDP_connected))
4898 		return (first); /* Nothing to print */
4899 
4900 	if (first) {
4901 		(void) printf("\nUDP: IPv6\n");
4902 		(void) printf(udp_hdr_v6);
4903 		first = B_FALSE;
4904 	}
4905 
4906 	ifnamep = (ude6->udp6IfIndex != 0) ?
4907 	    if_indextoname(ude6->udp6IfIndex, ifname) : NULL;
4908 
4909 	(void) printf("%-33s ",
4910 	    pr_ap6(&ude6->udp6LocalAddress,
4911 	    ude6->udp6LocalPort, "udp", lname, sizeof (lname)));
4912 	(void) printf("%-33s %-10s %s\n",
4913 	    ude6->udp6EntryInfo.ue_state == MIB2_UDP_connected ?
4914 	    pr_ap6(&ude6->udp6EntryInfo.ue_RemoteAddress,
4915 	    ude6->udp6EntryInfo.ue_RemotePort, "udp", lname, sizeof (lname)) :
4916 	    "",
4917 	    miudp_state(ude6->udp6EntryInfo.ue_state, attr),
4918 	    ifnamep == NULL ? "" : ifnamep);
4919 
4920 	/*
4921 	 * UDP sockets don't have remote attributes, so there's no need to
4922 	 * print them here.
4923 	 */
4924 
4925 	return (first);
4926 }
4927 
4928 /* ------------------------------ SCTP_REPORT------------------------------- */
4929 
4930 static const char sctp_hdr[] =
4931 "\nSCTP:";
4932 static const char sctp_hdr_normal[] =
4933 "        Local Address                   Remote Address          "
4934 "Swind  Send-Q Rwind  Recv-Q StrsI/O  State\n"
4935 "------------------------------- ------------------------------- "
4936 "------ ------ ------ ------ ------- -----------";
4937 
4938 static const char *
4939 nssctp_state(int state, const mib2_transportMLPEntry_t *attr)
4940 {
4941 	static char sctpsbuf[50];
4942 	const char *cp;
4943 
4944 	switch (state) {
4945 	case MIB2_SCTP_closed:
4946 		cp = "CLOSED";
4947 		break;
4948 	case MIB2_SCTP_cookieWait:
4949 		cp = "COOKIE_WAIT";
4950 		break;
4951 	case MIB2_SCTP_cookieEchoed:
4952 		cp = "COOKIE_ECHOED";
4953 		break;
4954 	case MIB2_SCTP_established:
4955 		cp = "ESTABLISHED";
4956 		break;
4957 	case MIB2_SCTP_shutdownPending:
4958 		cp = "SHUTDOWN_PENDING";
4959 		break;
4960 	case MIB2_SCTP_shutdownSent:
4961 		cp = "SHUTDOWN_SENT";
4962 		break;
4963 	case MIB2_SCTP_shutdownReceived:
4964 		cp = "SHUTDOWN_RECEIVED";
4965 		break;
4966 	case MIB2_SCTP_shutdownAckSent:
4967 		cp = "SHUTDOWN_ACK_SENT";
4968 		break;
4969 	case MIB2_SCTP_listen:
4970 		cp = "LISTEN";
4971 		break;
4972 	default:
4973 		(void) snprintf(sctpsbuf, sizeof (sctpsbuf),
4974 		    "UNKNOWN STATE(%d)", state);
4975 		cp = sctpsbuf;
4976 		break;
4977 	}
4978 
4979 	if (RSECflag && attr != NULL && attr->tme_flags != 0) {
4980 		if (cp != sctpsbuf) {
4981 			(void) strlcpy(sctpsbuf, cp, sizeof (sctpsbuf));
4982 			cp = sctpsbuf;
4983 		}
4984 		if (attr->tme_flags & MIB2_TMEF_PRIVATE)
4985 			(void) strlcat(sctpsbuf, " P", sizeof (sctpsbuf));
4986 		if (attr->tme_flags & MIB2_TMEF_SHARED)
4987 			(void) strlcat(sctpsbuf, " S", sizeof (sctpsbuf));
4988 	}
4989 
4990 	return (cp);
4991 }
4992 
4993 static const mib2_sctpConnRemoteEntry_t *
4994 sctp_getnext_rem(const mib_item_t **itemp,
4995     const mib2_sctpConnRemoteEntry_t *current, uint32_t associd)
4996 {
4997 	const mib_item_t *item = *itemp;
4998 	const mib2_sctpConnRemoteEntry_t	*sre;
4999 
5000 	for (; item != NULL; item = item->next_item, current = NULL) {
5001 		if (!(item->group == MIB2_SCTP &&
5002 		    item->mib_id == MIB2_SCTP_CONN_REMOTE)) {
5003 			continue;
5004 		}
5005 
5006 		if (current != NULL) {
5007 			/* LINTED: (note 1) */
5008 			sre = (const mib2_sctpConnRemoteEntry_t *)
5009 			    ((const char *)current + sctpRemoteEntrySize);
5010 		} else {
5011 			sre = item->valp;
5012 		}
5013 		for (; (char *)sre < (char *)item->valp + item->length;
5014 		    /* LINTED: (note 1) */
5015 		    sre = (const mib2_sctpConnRemoteEntry_t *)
5016 		    ((const char *)sre + sctpRemoteEntrySize)) {
5017 			if (sre->sctpAssocId != associd) {
5018 				continue;
5019 			}
5020 			*itemp = item;
5021 			return (sre);
5022 		}
5023 	}
5024 	*itemp = NULL;
5025 	return (NULL);
5026 }
5027 
5028 static const mib2_sctpConnLocalEntry_t *
5029 sctp_getnext_local(const mib_item_t **itemp,
5030     const mib2_sctpConnLocalEntry_t *current, uint32_t associd)
5031 {
5032 	const mib_item_t *item = *itemp;
5033 	const mib2_sctpConnLocalEntry_t	*sle;
5034 
5035 	for (; item != NULL; item = item->next_item, current = NULL) {
5036 		if (!(item->group == MIB2_SCTP &&
5037 		    item->mib_id == MIB2_SCTP_CONN_LOCAL)) {
5038 			continue;
5039 		}
5040 
5041 		if (current != NULL) {
5042 			/* LINTED: (note 1) */
5043 			sle = (const mib2_sctpConnLocalEntry_t *)
5044 			    ((const char *)current + sctpLocalEntrySize);
5045 		} else {
5046 			sle = item->valp;
5047 		}
5048 		for (; (char *)sle < (char *)item->valp + item->length;
5049 		    /* LINTED: (note 1) */
5050 		    sle = (const mib2_sctpConnLocalEntry_t *)
5051 		    ((const char *)sle + sctpLocalEntrySize)) {
5052 			if (sle->sctpAssocId != associd) {
5053 				continue;
5054 			}
5055 			*itemp = item;
5056 			return (sle);
5057 		}
5058 	}
5059 	*itemp = NULL;
5060 	return (NULL);
5061 }
5062 
5063 static void
5064 sctp_pr_addr(int type, char *name, int namelen, const in6_addr_t *addr,
5065     int port)
5066 {
5067 	ipaddr_t	v4addr;
5068 	in6_addr_t	v6addr;
5069 
5070 	/*
5071 	 * Address is either a v4 mapped or v6 addr. If
5072 	 * it's a v4 mapped, convert to v4 before
5073 	 * displaying.
5074 	 */
5075 	switch (type) {
5076 	    case MIB2_SCTP_ADDR_V4:
5077 		/* v4 */
5078 		v6addr = *addr;
5079 
5080 		IN6_V4MAPPED_TO_IPADDR(&v6addr, v4addr);
5081 		if (port > 0) {
5082 			(void) pr_ap(v4addr, port, "sctp", name, namelen);
5083 		} else {
5084 			(void) pr_addr(v4addr, name, namelen);
5085 		}
5086 		break;
5087 
5088 	    case MIB2_SCTP_ADDR_V6:
5089 		/* v6 */
5090 		if (port > 0) {
5091 			(void) pr_ap6(addr, port, "sctp", name, namelen);
5092 		} else {
5093 			(void) pr_addr6(addr, name, namelen);
5094 		}
5095 		break;
5096 
5097 	    default:
5098 		(void) snprintf(name, namelen, "<unknown addr type>");
5099 		break;
5100 	}
5101 }
5102 
5103 static void
5104 sctp_conn_report_item(const mib_item_t *head, const mib2_sctpConnEntry_t *sp,
5105     const mib2_transportMLPEntry_t *attr)
5106 {
5107 	char		lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5108 	char		fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5109 	const mib2_sctpConnRemoteEntry_t	*sre = NULL;
5110 	const mib2_sctpConnLocalEntry_t	*sle = NULL;
5111 	const mib_item_t *local = head;
5112 	const mib_item_t *remote = head;
5113 	uint32_t	id = sp->sctpAssocId;
5114 	boolean_t	printfirst = B_TRUE;
5115 
5116 	sctp_pr_addr(sp->sctpAssocRemPrimAddrType, fname, sizeof (fname),
5117 	    &sp->sctpAssocRemPrimAddr, sp->sctpAssocRemPort);
5118 	sctp_pr_addr(sp->sctpAssocRemPrimAddrType, lname, sizeof (lname),
5119 	    &sp->sctpAssocLocPrimAddr, sp->sctpAssocLocalPort);
5120 
5121 	(void) printf("%-31s %-31s %6u %6d %6u %6d %3d/%-3d %s\n",
5122 	    lname, fname,
5123 	    sp->sctpConnEntryInfo.ce_swnd,
5124 	    sp->sctpConnEntryInfo.ce_sendq,
5125 	    sp->sctpConnEntryInfo.ce_rwnd,
5126 	    sp->sctpConnEntryInfo.ce_recvq,
5127 	    sp->sctpAssocInStreams, sp->sctpAssocOutStreams,
5128 	    nssctp_state(sp->sctpAssocState, attr));
5129 
5130 	print_transport_label(attr);
5131 
5132 	if (!Vflag) {
5133 		return;
5134 	}
5135 
5136 	/* Print remote addresses/local addresses on following lines */
5137 	while ((sre = sctp_getnext_rem(&remote, sre, id)) != NULL) {
5138 		if (!IN6_ARE_ADDR_EQUAL(&sre->sctpAssocRemAddr,
5139 		    &sp->sctpAssocRemPrimAddr)) {
5140 			if (printfirst == B_TRUE) {
5141 				(void) fputs("\t<Remote: ", stdout);
5142 				printfirst = B_FALSE;
5143 			} else {
5144 				(void) fputs(", ", stdout);
5145 			}
5146 			sctp_pr_addr(sre->sctpAssocRemAddrType, fname,
5147 			    sizeof (fname), &sre->sctpAssocRemAddr, -1);
5148 			if (sre->sctpAssocRemAddrActive == MIB2_SCTP_ACTIVE) {
5149 				(void) fputs(fname, stdout);
5150 			} else {
5151 				(void) printf("(%s)", fname);
5152 			}
5153 		}
5154 	}
5155 	if (printfirst == B_FALSE) {
5156 		(void) puts(">");
5157 		printfirst = B_TRUE;
5158 	}
5159 	while ((sle = sctp_getnext_local(&local, sle, id)) != NULL) {
5160 		if (!IN6_ARE_ADDR_EQUAL(&sle->sctpAssocLocalAddr,
5161 		    &sp->sctpAssocLocPrimAddr)) {
5162 			if (printfirst == B_TRUE) {
5163 				(void) fputs("\t<Local: ", stdout);
5164 				printfirst = B_FALSE;
5165 			} else {
5166 				(void) fputs(", ", stdout);
5167 			}
5168 			sctp_pr_addr(sle->sctpAssocLocalAddrType, lname,
5169 			    sizeof (lname), &sle->sctpAssocLocalAddr, -1);
5170 			(void) fputs(lname, stdout);
5171 		}
5172 	}
5173 	if (printfirst == B_FALSE) {
5174 		(void) puts(">");
5175 	}
5176 }
5177 
5178 static void
5179 sctp_report(const mib_item_t *item)
5180 {
5181 	const mib_item_t		*head;
5182 	const mib2_sctpConnEntry_t	*sp;
5183 	boolean_t		first = B_TRUE;
5184 	mib2_transportMLPEntry_t **attrs, **aptr;
5185 	mib2_transportMLPEntry_t *attr;
5186 
5187 	/*
5188 	 * Preparation pass: the kernel returns separate entries for SCTP
5189 	 * connection table entries and Multilevel Port attributes.  We loop
5190 	 * through the attributes first and set up an array for each address
5191 	 * family.
5192 	 */
5193 	attrs = RSECflag ?
5194 	    gather_attrs(item, MIB2_SCTP, MIB2_SCTP_CONN, sctpEntrySize) :
5195 	    NULL;
5196 
5197 	aptr = attrs;
5198 	head = item;
5199 	for (; item != NULL; item = item->next_item) {
5200 
5201 		if (!(item->group == MIB2_SCTP &&
5202 		    item->mib_id == MIB2_SCTP_CONN))
5203 			continue;
5204 
5205 		for (sp = item->valp;
5206 		    (char *)sp < (char *)item->valp + item->length;
5207 		    /* LINTED: (note 1) */
5208 		    sp = (mib2_sctpConnEntry_t *)((char *)sp + sctpEntrySize)) {
5209 			attr = aptr == NULL ? NULL : *aptr++;
5210 			if (Aflag ||
5211 			    sp->sctpAssocState >= MIB2_SCTP_established) {
5212 				if (first == B_TRUE) {
5213 					(void) puts(sctp_hdr);
5214 					(void) puts(sctp_hdr_normal);
5215 					first = B_FALSE;
5216 				}
5217 				sctp_conn_report_item(head, sp, attr);
5218 			}
5219 		}
5220 	}
5221 	if (attrs != NULL)
5222 		free(attrs);
5223 }
5224 
5225 static char *
5226 plural(int n)
5227 {
5228 	return (n != 1 ? "s" : "");
5229 }
5230 
5231 static char *
5232 pluraly(int n)
5233 {
5234 	return (n != 1 ? "ies" : "y");
5235 }
5236 
5237 static char *
5238 plurales(int n)
5239 {
5240 	return (n != 1 ? "es" : "");
5241 }
5242 
5243 static char *
5244 pktscale(n)
5245 	int n;
5246 {
5247 	static char buf[6];
5248 	char t;
5249 
5250 	if (n < 1024) {
5251 		t = ' ';
5252 	} else if (n < 1024 * 1024) {
5253 		t = 'k';
5254 		n /= 1024;
5255 	} else if (n < 1024 * 1024 * 1024) {
5256 		t = 'm';
5257 		n /= 1024 * 1024;
5258 	} else {
5259 		t = 'g';
5260 		n /= 1024 * 1024 * 1024;
5261 	}
5262 
5263 	(void) snprintf(buf, sizeof (buf), "%4u%c", n, t);
5264 	return (buf);
5265 }
5266 
5267 /* --------------------- mrt_report (netstat -m) -------------------------- */
5268 
5269 static void
5270 mrt_report(mib_item_t *item)
5271 {
5272 	int		jtemp = 0;
5273 	struct vifctl	*vip;
5274 	vifi_t		vifi;
5275 	struct mfcctl	*mfccp;
5276 	int		numvifs = 0;
5277 	int		nmfc = 0;
5278 	char		abuf[MAXHOSTNAMELEN + 1];
5279 
5280 	if (!(family_selected(AF_INET)))
5281 		return;
5282 
5283 	/* 'for' loop 1: */
5284 	for (; item; item = item->next_item) {
5285 		if (Dflag) {
5286 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
5287 			(void) printf("Group = %d, mib_id = %d, "
5288 			    "length = %d, valp = 0x%p\n",
5289 			    item->group, item->mib_id, item->length,
5290 			    item->valp);
5291 		}
5292 		if (item->group != EXPER_DVMRP)
5293 			continue; /* 'for' loop 1 */
5294 
5295 		switch (item->mib_id) {
5296 
5297 		case EXPER_DVMRP_VIF:
5298 			if (Dflag)
5299 				(void) printf("%u records for ipVifTable:\n",
5300 				    item->length/sizeof (struct vifctl));
5301 			if (item->length/sizeof (struct vifctl) == 0) {
5302 				(void) puts("\nVirtual Interface Table is "
5303 				    "empty");
5304 				break;
5305 			}
5306 
5307 			(void) puts("\nVirtual Interface Table\n"
5308 			    " Vif Threshold Rate_Limit Local-Address"
5309 			    "   Remote-Address     Pkt_in   Pkt_out");
5310 
5311 			/* 'for' loop 2: */
5312 			for (vip = (struct vifctl *)item->valp;
5313 			    (char *)vip < (char *)item->valp + item->length;
5314 			    /* LINTED: (note 1) */
5315 			    vip = (struct vifctl *)((char *)vip +
5316 			    vifctlSize)) {
5317 				if (vip->vifc_lcl_addr.s_addr == 0)
5318 					continue; /* 'for' loop 2 */
5319 				/* numvifs = vip->vifc_vifi; */
5320 
5321 				numvifs++;
5322 				(void) printf("  %2u       %3u       "
5323 				    "%4u %-15.15s",
5324 				    vip->vifc_vifi,
5325 				    vip->vifc_threshold,
5326 				    vip->vifc_rate_limit,
5327 				    pr_addr(vip->vifc_lcl_addr.s_addr,
5328 				    abuf, sizeof (abuf)));
5329 				(void) printf(" %-15.15s  %8u  %8u\n",
5330 				    (vip->vifc_flags & VIFF_TUNNEL) ?
5331 				    pr_addr(vip->vifc_rmt_addr.s_addr,
5332 				    abuf, sizeof (abuf)) : "",
5333 				    vip->vifc_pkt_in,
5334 				    vip->vifc_pkt_out);
5335 			} /* 'for' loop 2 ends */
5336 
5337 			(void) printf("Numvifs: %d\n", numvifs);
5338 			break;
5339 
5340 		case EXPER_DVMRP_MRT:
5341 			if (Dflag)
5342 				(void) printf("%u records for ipMfcTable:\n",
5343 					item->length/sizeof (struct vifctl));
5344 			if (item->length/sizeof (struct vifctl) == 0) {
5345 				(void) puts("\nMulticast Forwarding Cache is "
5346 				    "empty");
5347 				break;
5348 			}
5349 
5350 			(void) puts("\nMulticast Forwarding Cache\n"
5351 			    "  Origin-Subnet                 Mcastgroup      "
5352 			    "# Pkts  In-Vif  Out-vifs/Forw-ttl");
5353 
5354 			for (mfccp = (struct mfcctl *)item->valp;
5355 			    (char *)mfccp < (char *)item->valp + item->length;
5356 			    /* LINTED: (note 1) */
5357 			    mfccp = (struct mfcctl *)((char *)mfccp +
5358 			    mfcctlSize)) {
5359 
5360 				nmfc++;
5361 				(void) printf("  %-30.15s",
5362 				    pr_addr(mfccp->mfcc_origin.s_addr,
5363 				    abuf, sizeof (abuf)));
5364 				(void) printf("%-15.15s  %6s  %3u    ",
5365 				    pr_net(mfccp->mfcc_mcastgrp.s_addr,
5366 					mfccp->mfcc_mcastgrp.s_addr,
5367 					abuf, sizeof (abuf)),
5368 				    pktscale((int)mfccp->mfcc_pkt_cnt),
5369 					mfccp->mfcc_parent);
5370 
5371 				for (vifi = 0; vifi < MAXVIFS; ++vifi) {
5372 					if (mfccp->mfcc_ttls[vifi]) {
5373 						(void) printf("      %u (%u)",
5374 						    vifi,
5375 						    mfccp->mfcc_ttls[vifi]);
5376 					}
5377 
5378 				}
5379 				(void) putchar('\n');
5380 			}
5381 			(void) printf("\nTotal no. of entries in cache: %d\n",
5382 			    nmfc);
5383 			break;
5384 		}
5385 	} /* 'for' loop 1 ends */
5386 	(void) putchar('\n');
5387 	(void) fflush(stdout);
5388 }
5389 
5390 /*
5391  * Get the stats for the cache named 'name'.  If prefix != 0, then
5392  * interpret the name as a prefix, and sum up stats for all caches
5393  * named 'name*'.
5394  */
5395 static void
5396 kmem_cache_stats(char *title, char *name, int prefix, int64_t *total_bytes)
5397 {
5398 	int len;
5399 	int alloc;
5400 	int64_t total_alloc = 0;
5401 	int alloc_fail, total_alloc_fail = 0;
5402 	int buf_size = 0;
5403 	int buf_avail;
5404 	int buf_total;
5405 	int buf_max, total_buf_max = 0;
5406 	int buf_inuse, total_buf_inuse = 0;
5407 	kstat_t *ksp;
5408 	char buf[256];
5409 
5410 	len = prefix ? strlen(name) : 256;
5411 
5412 	/* 'for' loop 1: */
5413 	for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
5414 
5415 		if (strcmp(ksp->ks_class, "kmem_cache") != 0)
5416 			continue; /* 'for' loop 1 */
5417 
5418 		/*
5419 		 * Hack alert: because of the way streams messages are
5420 		 * allocated, every constructed free dblk has an associated
5421 		 * mblk.  From the allocator's viewpoint those mblks are
5422 		 * allocated (because they haven't been freed), but from
5423 		 * our viewpoint they're actually free (because they're
5424 		 * not currently in use).  To account for this caching
5425 		 * effect we subtract the total constructed free dblks
5426 		 * from the total allocated mblks to derive mblks in use.
5427 		 */
5428 		if (strcmp(name, "streams_mblk") == 0 &&
5429 		    strncmp(ksp->ks_name, "streams_dblk", 12) == 0) {
5430 			(void) safe_kstat_read(kc, ksp, NULL);
5431 			total_buf_inuse -=
5432 				kstat_named_value(ksp, "buf_constructed");
5433 			continue; /* 'for' loop 1 */
5434 		}
5435 
5436 		if (strncmp(ksp->ks_name, name, len) != 0)
5437 			continue; /* 'for' loop 1 */
5438 
5439 		(void) safe_kstat_read(kc, ksp, NULL);
5440 
5441 		alloc		= kstat_named_value(ksp, "alloc");
5442 		alloc_fail	= kstat_named_value(ksp, "alloc_fail");
5443 		buf_size	= kstat_named_value(ksp, "buf_size");
5444 		buf_avail	= kstat_named_value(ksp, "buf_avail");
5445 		buf_total	= kstat_named_value(ksp, "buf_total");
5446 		buf_max		= kstat_named_value(ksp, "buf_max");
5447 		buf_inuse	= buf_total - buf_avail;
5448 
5449 		if (Vflag && prefix) {
5450 			(void) snprintf(buf, sizeof (buf), "%s%s", title,
5451 			    ksp->ks_name + len);
5452 			(void) printf("    %-18s %6u %9u %11u %11u\n",
5453 			    buf, buf_inuse, buf_max, alloc, alloc_fail);
5454 		}
5455 
5456 		total_alloc		+= alloc;
5457 		total_alloc_fail	+= alloc_fail;
5458 		total_buf_max		+= buf_max;
5459 		total_buf_inuse		+= buf_inuse;
5460 		*total_bytes		+= (int64_t)buf_inuse * buf_size;
5461 	} /* 'for' loop 1 ends */
5462 
5463 	if (buf_size == 0) {
5464 		(void) printf("%-22s [couldn't find statistics for %s]\n",
5465 			title, name);
5466 		return;
5467 	}
5468 
5469 	if (Vflag && prefix)
5470 		(void) snprintf(buf, sizeof (buf), "%s_total", title);
5471 	else
5472 		(void) snprintf(buf, sizeof (buf), "%s", title);
5473 
5474 	(void) printf("%-22s %6d %9d %11lld %11d\n", buf,
5475 		total_buf_inuse, total_buf_max, total_alloc, total_alloc_fail);
5476 }
5477 
5478 static void
5479 m_report(void)
5480 {
5481 	int64_t total_bytes = 0;
5482 
5483 	(void) puts("streams allocation:");
5484 	(void) printf("%63s\n", "cumulative  allocation");
5485 	(void) printf("%63s\n",
5486 	    "current   maximum       total    failures");
5487 
5488 	kmem_cache_stats("streams",
5489 	    "stream_head_cache", 0, &total_bytes);
5490 	kmem_cache_stats("queues", "queue_cache", 0, &total_bytes);
5491 	kmem_cache_stats("mblk", "streams_mblk", 0, &total_bytes);
5492 	kmem_cache_stats("dblk", "streams_dblk", 1, &total_bytes);
5493 	kmem_cache_stats("linkblk", "linkinfo_cache", 0, &total_bytes);
5494 	kmem_cache_stats("syncq", "syncq_cache", 0, &total_bytes);
5495 	kmem_cache_stats("qband", "qband_cache", 0, &total_bytes);
5496 
5497 	(void) printf("\n%lld Kbytes allocated for streams data\n",
5498 		total_bytes / 1024);
5499 
5500 	(void) putchar('\n');
5501 	(void) fflush(stdout);
5502 }
5503 
5504 /* --------------------------------- */
5505 
5506 /*
5507  * Print an IPv4 address. Remove the matching part of the domain name
5508  * from the returned name.
5509  */
5510 static char *
5511 pr_addr(uint_t addr, char *dst, uint_t dstlen)
5512 {
5513 	char			*cp;
5514 	struct hostent		*hp = NULL;
5515 	static char		domain[MAXHOSTNAMELEN + 1];
5516 	static boolean_t	first = B_TRUE;
5517 	int			error_num;
5518 
5519 	if (first) {
5520 		first = B_FALSE;
5521 		if (sysinfo(SI_HOSTNAME, domain, MAXHOSTNAMELEN) != -1 &&
5522 		    (cp = strchr(domain, '.'))) {
5523 			(void) strncpy(domain, cp + 1, sizeof (domain));
5524 		} else
5525 			domain[0] = 0;
5526 	}
5527 	cp = NULL;
5528 	if (!Nflag) {
5529 		hp = getipnodebyaddr((char *)&addr, sizeof (uint_t), AF_INET,
5530 		    &error_num);
5531 		if (hp) {
5532 			if ((cp = strchr(hp->h_name, '.')) != NULL &&
5533 			    strcasecmp(cp + 1, domain) == 0)
5534 				*cp = 0;
5535 			cp = hp->h_name;
5536 		}
5537 	}
5538 	if (cp != NULL) {
5539 		(void) strncpy(dst, cp, dstlen);
5540 		dst[dstlen - 1] = 0;
5541 	} else {
5542 		(void) inet_ntop(AF_INET, (char *)&addr, dst, dstlen);
5543 	}
5544 	if (hp != NULL)
5545 		freehostent(hp);
5546 	return (dst);
5547 }
5548 
5549 /*
5550  * Print a non-zero IPv4 address.  Print "    --" if the address is zero.
5551  */
5552 static char *
5553 pr_addrnz(ipaddr_t addr, char *dst, uint_t dstlen)
5554 {
5555 	if (addr == INADDR_ANY) {
5556 		(void) strlcpy(dst, "    --", dstlen);
5557 		return (dst);
5558 	}
5559 	return (pr_addr(addr, dst, dstlen));
5560 }
5561 
5562 /*
5563  * Print an IPv6 address. Remove the matching part of the domain name
5564  * from the returned name.
5565  */
5566 static char *
5567 pr_addr6(const struct in6_addr *addr, char *dst, uint_t dstlen)
5568 {
5569 	char			*cp;
5570 	struct hostent		*hp = NULL;
5571 	static char		domain[MAXHOSTNAMELEN + 1];
5572 	static boolean_t	first = B_TRUE;
5573 	int			error_num;
5574 
5575 	if (first) {
5576 		first = B_FALSE;
5577 		if (sysinfo(SI_HOSTNAME, domain, MAXHOSTNAMELEN) != -1 &&
5578 		    (cp = strchr(domain, '.'))) {
5579 			(void) strncpy(domain, cp + 1, sizeof (domain));
5580 		} else
5581 			domain[0] = 0;
5582 	}
5583 	cp = NULL;
5584 	if (!Nflag) {
5585 		hp = getipnodebyaddr((char *)addr,
5586 		    sizeof (struct in6_addr), AF_INET6, &error_num);
5587 		if (hp) {
5588 			if ((cp = strchr(hp->h_name, '.')) != NULL &&
5589 			    strcasecmp(cp + 1, domain) == 0)
5590 				*cp = 0;
5591 			cp = hp->h_name;
5592 		}
5593 	}
5594 	if (cp != NULL) {
5595 		(void) strncpy(dst, cp, dstlen);
5596 		dst[dstlen - 1] = 0;
5597 	} else {
5598 		(void) inet_ntop(AF_INET6, (void *)addr, dst, dstlen);
5599 	}
5600 	if (hp != NULL)
5601 		freehostent(hp);
5602 	return (dst);
5603 }
5604 
5605 /* For IPv4 masks */
5606 static char *
5607 pr_mask(uint_t addr, char *dst, uint_t dstlen)
5608 {
5609 	uint8_t	*ip_addr = (uint8_t *)&addr;
5610 
5611 	(void) snprintf(dst, dstlen, "%d.%d.%d.%d",
5612 	    ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3]);
5613 	return (dst);
5614 }
5615 
5616 /*
5617  * For ipv6 masks format is : dest/mask
5618  * Does not print /128 to save space in printout. H flag carries this notion.
5619  */
5620 static char *
5621 pr_prefix6(const struct in6_addr *addr, uint_t prefixlen, char *dst,
5622     uint_t dstlen)
5623 {
5624 	char *cp;
5625 
5626 	if (IN6_IS_ADDR_UNSPECIFIED(addr) && prefixlen == 0) {
5627 		(void) strncpy(dst, "default", dstlen);
5628 		dst[dstlen - 1] = 0;
5629 		return (dst);
5630 	}
5631 
5632 	(void) pr_addr6(addr, dst, dstlen);
5633 	if (prefixlen != IPV6_ABITS) {
5634 		/* How much room is left? */
5635 		cp = strchr(dst, '\0');
5636 		if (dst + dstlen > cp) {
5637 			dstlen -= (cp - dst);
5638 			(void) snprintf(cp, dstlen, "/%d", prefixlen);
5639 		}
5640 	}
5641 	return (dst);
5642 }
5643 
5644 /* Print IPv4 address and port */
5645 static char *
5646 pr_ap(uint_t addr, uint_t port, char *proto,
5647     char *dst, uint_t dstlen)
5648 {
5649 	char *cp;
5650 
5651 	if (addr == INADDR_ANY) {
5652 		(void) strncpy(dst, "      *", dstlen);
5653 		dst[dstlen - 1] = 0;
5654 	} else {
5655 		(void) pr_addr(addr, dst, dstlen);
5656 	}
5657 	/* How much room is left? */
5658 	cp = strchr(dst, '\0');
5659 	if (dst + dstlen > cp + 1) {
5660 		*cp++ = '.';
5661 		dstlen -= (cp - dst);
5662 		dstlen--;
5663 		(void) portname(port, proto, cp, dstlen);
5664 	}
5665 	return (dst);
5666 }
5667 
5668 /* Print IPv6 address and port */
5669 static char *
5670 pr_ap6(const in6_addr_t *addr, uint_t port, char *proto,
5671     char *dst, uint_t dstlen)
5672 {
5673 	char *cp;
5674 
5675 	if (IN6_IS_ADDR_UNSPECIFIED(addr)) {
5676 		(void) strncpy(dst, "      *", dstlen);
5677 		dst[dstlen - 1] = 0;
5678 	} else {
5679 		(void) pr_addr6(addr, dst, dstlen);
5680 	}
5681 	/* How much room is left? */
5682 	cp = strchr(dst, '\0');
5683 	if (dst + dstlen + 1 > cp) {
5684 		*cp++ = '.';
5685 		dstlen -= (cp - dst);
5686 		dstlen--;
5687 		(void) portname(port, proto, cp, dstlen);
5688 	}
5689 	return (dst);
5690 }
5691 
5692 /*
5693  * Return the name of the network whose address is given. The address is
5694  * assumed to be that of a net or subnet, not a host.
5695  */
5696 static char *
5697 pr_net(uint_t addr, uint_t mask, char *dst, uint_t dstlen)
5698 {
5699 	char		*cp = NULL;
5700 	struct netent	*np = NULL;
5701 	struct hostent	*hp = NULL;
5702 	uint_t		net;
5703 	int		subnetshift;
5704 	int		error_num;
5705 
5706 	if (addr == INADDR_ANY && mask == INADDR_ANY) {
5707 		(void) strncpy(dst, "default", dstlen);
5708 		dst[dstlen - 1] = 0;
5709 		return (dst);
5710 	}
5711 
5712 	if (!Nflag && addr) {
5713 		if (mask == 0) {
5714 			if (IN_CLASSA(addr)) {
5715 				mask = (uint_t)IN_CLASSA_NET;
5716 				subnetshift = 8;
5717 			} else if (IN_CLASSB(addr)) {
5718 				mask = (uint_t)IN_CLASSB_NET;
5719 				subnetshift = 8;
5720 			} else {
5721 				mask = (uint_t)IN_CLASSC_NET;
5722 				subnetshift = 4;
5723 			}
5724 			/*
5725 			 * If there are more bits than the standard mask
5726 			 * would suggest, subnets must be in use. Guess at
5727 			 * the subnet mask, assuming reasonable width subnet
5728 			 * fields.
5729 			 */
5730 			while (addr & ~mask)
5731 				/* compiler doesn't sign extend! */
5732 				mask = (mask | ((int)mask >> subnetshift));
5733 		}
5734 		net = addr & mask;
5735 		while ((mask & 1) == 0)
5736 			mask >>= 1, net >>= 1;
5737 		np = getnetbyaddr(net, AF_INET);
5738 		if (np && np->n_net == net)
5739 			cp = np->n_name;
5740 		else {
5741 			/*
5742 			 * Look for subnets in hosts map.
5743 			 */
5744 			hp = getipnodebyaddr((char *)&addr, sizeof (uint_t),
5745 			    AF_INET, &error_num);
5746 			if (hp)
5747 				cp = hp->h_name;
5748 		}
5749 	}
5750 	if (cp != NULL) {
5751 		(void) strncpy(dst, cp, dstlen);
5752 		dst[dstlen - 1] = 0;
5753 	} else {
5754 		(void) inet_ntop(AF_INET, (char *)&addr, dst, dstlen);
5755 	}
5756 	if (hp != NULL)
5757 		freehostent(hp);
5758 	return (dst);
5759 }
5760 
5761 /*
5762  * Return the name of the network whose address is given.
5763  * The address is assumed to be a host address.
5764  */
5765 static char *
5766 pr_netaddr(uint_t addr, uint_t mask, char *dst, uint_t dstlen)
5767 {
5768 	char		*cp = NULL;
5769 	struct netent	*np = NULL;
5770 	struct hostent	*hp = NULL;
5771 	uint_t		net;
5772 	uint_t		netshifted;
5773 	int		subnetshift;
5774 	struct in_addr in;
5775 	int		error_num;
5776 	uint_t		nbo_addr = addr;	/* network byte order */
5777 
5778 	addr = ntohl(addr);
5779 	mask = ntohl(mask);
5780 	if (addr == INADDR_ANY && mask == INADDR_ANY) {
5781 		(void) strncpy(dst, "default", dstlen);
5782 		dst[dstlen - 1] = 0;
5783 		return (dst);
5784 	}
5785 
5786 	/* Figure out network portion of address (with host portion = 0) */
5787 	if (addr) {
5788 		/* Try figuring out mask if unknown (all 0s). */
5789 		if (mask == 0) {
5790 			if (IN_CLASSA(addr)) {
5791 				mask = (uint_t)IN_CLASSA_NET;
5792 				subnetshift = 8;
5793 			} else if (IN_CLASSB(addr)) {
5794 				mask = (uint_t)IN_CLASSB_NET;
5795 				subnetshift = 8;
5796 			} else {
5797 				mask = (uint_t)IN_CLASSC_NET;
5798 				subnetshift = 4;
5799 			}
5800 			/*
5801 			 * If there are more bits than the standard mask
5802 			 * would suggest, subnets must be in use. Guess at
5803 			 * the subnet mask, assuming reasonable width subnet
5804 			 * fields.
5805 			 */
5806 			while (addr & ~mask)
5807 				/* compiler doesn't sign extend! */
5808 				mask = (mask | ((int)mask >> subnetshift));
5809 		}
5810 		net = netshifted = addr & mask;
5811 		while ((mask & 1) == 0)
5812 			mask >>= 1, netshifted >>= 1;
5813 	}
5814 	else
5815 		net = netshifted = 0;
5816 
5817 	/* Try looking up name unless -n was specified. */
5818 	if (!Nflag) {
5819 		np = getnetbyaddr(netshifted, AF_INET);
5820 		if (np && np->n_net == netshifted)
5821 			cp = np->n_name;
5822 		else {
5823 			/*
5824 			 * Look for subnets in hosts map.
5825 			 */
5826 			hp = getipnodebyaddr((char *)&nbo_addr, sizeof (uint_t),
5827 			    AF_INET, &error_num);
5828 			if (hp)
5829 				cp = hp->h_name;
5830 		}
5831 
5832 		if (cp != NULL) {
5833 			(void) strncpy(dst, cp, dstlen);
5834 			dst[dstlen - 1] = 0;
5835 			if (hp != NULL)
5836 				freehostent(hp);
5837 			return (dst);
5838 		}
5839 		/*
5840 		 * No name found for net: fallthru and return in decimal
5841 		 * dot notation.
5842 		 */
5843 	}
5844 
5845 	in.s_addr = htonl(net);
5846 	(void) inet_ntop(AF_INET, (char *)&in, dst, dstlen);
5847 	if (hp != NULL)
5848 		freehostent(hp);
5849 	return (dst);
5850 }
5851 
5852 /*
5853  * Return the filter mode as a string:
5854  *	1 => "INCLUDE"
5855  *	2 => "EXCLUDE"
5856  *	otherwise "<unknown>"
5857  */
5858 static char *
5859 fmodestr(uint_t fmode)
5860 {
5861 	switch (fmode) {
5862 	case 1:
5863 		return ("INCLUDE");
5864 	case 2:
5865 		return ("EXCLUDE");
5866 	default:
5867 		return ("<unknown>");
5868 	}
5869 }
5870 
5871 #define	MAX_STRING_SIZE	256
5872 
5873 static const char *
5874 pr_secattr(const sec_attr_list_t *attrs)
5875 {
5876 	int i;
5877 	char buf[MAX_STRING_SIZE + 1], *cp;
5878 	static char *sbuf;
5879 	static size_t sbuf_len;
5880 	struct rtsa_s rtsa;
5881 	const sec_attr_list_t *aptr;
5882 
5883 	if (!RSECflag || attrs == NULL)
5884 		return ("");
5885 
5886 	for (aptr = attrs, i = 1; aptr != NULL; aptr = aptr->sal_next)
5887 		i += MAX_STRING_SIZE;
5888 	if (i > sbuf_len) {
5889 		cp = realloc(sbuf, i);
5890 		if (cp == NULL) {
5891 			perror("realloc security attribute buffer");
5892 			return ("");
5893 		}
5894 		sbuf_len = i;
5895 		sbuf = cp;
5896 	}
5897 
5898 	cp = sbuf;
5899 	while (attrs != NULL) {
5900 		const mib2_ipAttributeEntry_t *iae = attrs->sal_attr;
5901 
5902 		/* note: effectively hard-coded in rtsa_keyword */
5903 		rtsa.rtsa_mask = RTSA_CIPSO | RTSA_SLRANGE | RTSA_DOI;
5904 		rtsa.rtsa_slrange = iae->iae_slrange;
5905 		rtsa.rtsa_doi = iae->iae_doi;
5906 
5907 		(void) snprintf(cp, MAX_STRING_SIZE,
5908 		    "<%s>%s ", rtsa_to_str(&rtsa, buf, sizeof (buf)),
5909 		    attrs->sal_next == NULL ? "" : ",");
5910 		cp += strlen(cp);
5911 		attrs = attrs->sal_next;
5912 	}
5913 	*cp = '\0';
5914 
5915 	return (sbuf);
5916 }
5917 
5918 /*
5919  * Pretty print a port number. If the Nflag was
5920  * specified, use numbers instead of names.
5921  */
5922 static char *
5923 portname(uint_t port, char *proto, char *dst, uint_t dstlen)
5924 {
5925 	struct servent *sp = NULL;
5926 
5927 	if (!Nflag && port)
5928 		sp = getservbyport(htons(port), proto);
5929 	if (sp || port == 0)
5930 		(void) snprintf(dst, dstlen, "%.*s", MAXHOSTNAMELEN,
5931 				sp ? sp->s_name : "*");
5932 	else
5933 		(void) snprintf(dst, dstlen, "%d", port);
5934 	dst[dstlen - 1] = 0;
5935 	return (dst);
5936 }
5937 
5938 /*PRINTFLIKE2*/
5939 void
5940 fail(int do_perror, char *message, ...)
5941 {
5942 	va_list args;
5943 
5944 	va_start(args, message);
5945 	(void) fputs("netstat: ", stderr);
5946 	(void) vfprintf(stderr, message, args);
5947 	va_end(args);
5948 	if (do_perror)
5949 		(void) fprintf(stderr, ": %s", strerror(errno));
5950 	(void) fputc('\n', stderr);
5951 	exit(2);
5952 }
5953 
5954 /*
5955  * Return value of named statistic for given kstat_named kstat;
5956  * return 0LL if named statistic is not in list (use "ll" as a
5957  * type qualifier when printing 64-bit int's with printf() )
5958  */
5959 static uint64_t
5960 kstat_named_value(kstat_t *ksp, char *name)
5961 {
5962 	kstat_named_t *knp;
5963 	uint64_t value;
5964 
5965 	if (ksp == NULL)
5966 		return (0LL);
5967 
5968 	knp = kstat_data_lookup(ksp, name);
5969 	if (knp == NULL)
5970 		return (0LL);
5971 
5972 	switch (knp->data_type) {
5973 	case KSTAT_DATA_INT32:
5974 	case KSTAT_DATA_UINT32:
5975 		value = (uint64_t)(knp->value.ui32);
5976 		break;
5977 	case KSTAT_DATA_INT64:
5978 	case KSTAT_DATA_UINT64:
5979 		value = knp->value.ui64;
5980 		break;
5981 	default:
5982 		value = 0LL;
5983 		break;
5984 	}
5985 
5986 	return (value);
5987 }
5988 
5989 kid_t
5990 safe_kstat_read(kstat_ctl_t *kc, kstat_t *ksp, void *data)
5991 {
5992 	kid_t kstat_chain_id = kstat_read(kc, ksp, data);
5993 
5994 	if (kstat_chain_id == -1)
5995 		fail(1, "kstat_read(%p, '%s') failed", (void *)kc,
5996 		    ksp->ks_name);
5997 	return (kstat_chain_id);
5998 }
5999 
6000 /*
6001  * Parse a list of IRE flag characters into a bit field.
6002  */
6003 static uint_t
6004 flag_bits(const char *arg)
6005 {
6006 	const char *cp;
6007 	uint_t val;
6008 
6009 	if (*arg == '\0')
6010 		fatal(1, "missing flag list\n");
6011 
6012 	val = 0;
6013 	while (*arg != '\0') {
6014 		if ((cp = strchr(flag_list, *arg)) == NULL)
6015 			fatal(1, "%c: illegal flag\n", *arg);
6016 		val |= 1 << (cp - flag_list);
6017 		arg++;
6018 	}
6019 	return (val);
6020 }
6021 
6022 /*
6023  * Handle -f argument.  Validate input format, sort by keyword, and
6024  * save off digested results.
6025  */
6026 static void
6027 process_filter(char *arg)
6028 {
6029 	int idx;
6030 	int klen = 0;
6031 	char *cp, *cp2;
6032 	int val;
6033 	filter_t *newf;
6034 	struct hostent *hp;
6035 	int error_num;
6036 	uint8_t *ucp;
6037 	int maxv;
6038 
6039 	/* Look up the keyword first */
6040 	if (strchr(arg, ':') == NULL) {
6041 		idx = FK_AF;
6042 	} else {
6043 		for (idx = 0; idx < NFILTERKEYS; idx++) {
6044 			klen = strlen(filter_keys[idx]);
6045 			if (strncmp(filter_keys[idx], arg, klen) == 0 &&
6046 			    arg[klen] == ':')
6047 				break;
6048 		}
6049 		if (idx >= NFILTERKEYS)
6050 			fatal(1, "%s: unknown filter keyword\n", arg);
6051 
6052 		/* Advance past keyword and separator. */
6053 		arg += klen + 1;
6054 	}
6055 
6056 	if ((newf = malloc(sizeof (*newf))) == NULL) {
6057 		perror("filter");
6058 		exit(1);
6059 	}
6060 	switch (idx) {
6061 	case FK_AF:
6062 		if (strcmp(arg, "inet") == 0) {
6063 			newf->u.f_family = AF_INET;
6064 		} else if (strcmp(arg, "inet6") == 0) {
6065 			newf->u.f_family = AF_INET6;
6066 		} else if (strcmp(arg, "unix") == 0) {
6067 			newf->u.f_family = AF_UNIX;
6068 		} else {
6069 			newf->u.f_family = strtol(arg, &cp, 0);
6070 			if (arg == cp || *cp != '\0')
6071 				fatal(1, "%s: unknown address family.\n", arg);
6072 		}
6073 		break;
6074 
6075 	case FK_OUTIF:
6076 		if (strcmp(arg, "none") == 0) {
6077 			newf->u.f_ifname = NULL;
6078 			break;
6079 		}
6080 		if (strcmp(arg, "any") == 0) {
6081 			newf->u.f_ifname = "";
6082 			break;
6083 		}
6084 		val = strtol(arg, &cp, 0);
6085 		if (val <= 0 || arg == cp || cp[0] != '\0') {
6086 			if ((val = if_nametoindex(arg)) == 0) {
6087 				perror(arg);
6088 				exit(1);
6089 			}
6090 		}
6091 		newf->u.f_ifname = arg;
6092 		break;
6093 
6094 	case FK_DST:
6095 		V4MASK_TO_V6(IP_HOST_MASK, newf->u.a.f_mask);
6096 		if (strcmp(arg, "any") == 0) {
6097 			/* Special semantics; any address *but* zero */
6098 			newf->u.a.f_address = NULL;
6099 			(void) memset(&newf->u.a.f_mask, 0,
6100 			    sizeof (newf->u.a.f_mask));
6101 			break;
6102 		}
6103 		if (strcmp(arg, "none") == 0) {
6104 			newf->u.a.f_address = NULL;
6105 			break;
6106 		}
6107 		if ((cp = strrchr(arg, '/')) != NULL)
6108 			*cp++ = '\0';
6109 		hp = getipnodebyname(arg, AF_INET6, AI_V4MAPPED|AI_ALL,
6110 		    &error_num);
6111 		if (hp == NULL)
6112 			fatal(1, "%s: invalid or unknown host address\n", arg);
6113 		newf->u.a.f_address = hp;
6114 		if (cp == NULL) {
6115 			V4MASK_TO_V6(IP_HOST_MASK, newf->u.a.f_mask);
6116 		} else {
6117 			val = strtol(cp, &cp2, 0);
6118 			if (cp != cp2 && cp2[0] == '\0') {
6119 				/*
6120 				 * If decode as "/n" works, then translate
6121 				 * into a mask.
6122 				 */
6123 				if (hp->h_addr_list[0] != NULL &&
6124 				    /* LINTED: (note 1) */
6125 				    IN6_IS_ADDR_V4MAPPED((in6_addr_t
6126 					*)hp->h_addr_list[0])) {
6127 					maxv = IP_ABITS;
6128 				} else {
6129 					maxv = IPV6_ABITS;
6130 				}
6131 				if (val < 0 || val >= maxv)
6132 					fatal(1, "%d: not in range 0 to %d\n",
6133 					    val, maxv - 1);
6134 				if (maxv == IP_ABITS)
6135 					val += IPV6_ABITS - IP_ABITS;
6136 				ucp = newf->u.a.f_mask.s6_addr;
6137 				while (val >= 8)
6138 					*ucp++ = 0xff, val -= 8;
6139 				*ucp++ = (0xff << (8 - val)) & 0xff;
6140 				while (ucp < newf->u.a.f_mask.s6_addr +
6141 				    sizeof (newf->u.a.f_mask.s6_addr))
6142 					*ucp++ = 0;
6143 				/* Otherwise, try as numeric address */
6144 			} else if (inet_pton(AF_INET6,
6145 			    cp, &newf->u.a.f_mask) <= 0) {
6146 				fatal(1, "%s: illegal mask format\n", cp);
6147 			}
6148 		}
6149 		break;
6150 
6151 	case FK_FLAGS:
6152 		if (*arg == '+') {
6153 			newf->u.f.f_flagset = flag_bits(arg + 1);
6154 			newf->u.f.f_flagclear = 0;
6155 		} else if (*arg == '-') {
6156 			newf->u.f.f_flagset = 0;
6157 			newf->u.f.f_flagclear = flag_bits(arg + 1);
6158 		} else {
6159 			newf->u.f.f_flagset = flag_bits(arg);
6160 			newf->u.f.f_flagclear = ~newf->u.f.f_flagset;
6161 		}
6162 		break;
6163 
6164 	default:
6165 		assert(0);
6166 	}
6167 	newf->f_next = filters[idx];
6168 	filters[idx] = newf;
6169 }
6170 
6171 /* Determine if user wants this address family printed. */
6172 static boolean_t
6173 family_selected(int family)
6174 {
6175 	const filter_t *fp;
6176 
6177 	if (v4compat && family == AF_INET6)
6178 		return (B_FALSE);
6179 	if ((fp = filters[FK_AF]) == NULL)
6180 		return (B_TRUE);
6181 	while (fp != NULL) {
6182 		if (fp->u.f_family == family)
6183 			return (B_TRUE);
6184 		fp = fp->f_next;
6185 	}
6186 	return (B_FALSE);
6187 }
6188 
6189 /*
6190  * print the usage line
6191  */
6192 static void
6193 usage(char *cmdname)
6194 {
6195 	(void) fprintf(stderr, "usage: %s [-anv] [-f address_family]\n",
6196 	    cmdname);
6197 	(void) fprintf(stderr, "       %s [-n] [-f address_family] "
6198 	    "[-P protocol] [-g | -p | -s [interval [count]]]\n", cmdname);
6199 	(void) fprintf(stderr, "       %s -m [-v] "
6200 	    "[interval [count]]\n", cmdname);
6201 	(void) fprintf(stderr, "       %s -i [-I interface] [-an] "
6202 	    "[-f address_family] [interval [count]]\n", cmdname);
6203 	(void) fprintf(stderr, "       %s -r [-anv] "
6204 	    "[-f address_family|filter]\n", cmdname);
6205 	(void) fprintf(stderr, "       %s -M [-ns] [-f address_family]\n",
6206 	    cmdname);
6207 	(void) fprintf(stderr, "       %s -D [-I interface] "
6208 	    "[-f address_family]\n", cmdname);
6209 	exit(EXIT_FAILURE);
6210 }
6211 
6212 /*
6213  * fatal: print error message to stderr and
6214  * call exit(errcode)
6215  */
6216 /*PRINTFLIKE2*/
6217 static void
6218 fatal(int errcode, char *format, ...)
6219 {
6220 	va_list argp;
6221 
6222 	if (format == NULL)
6223 		return;
6224 
6225 	va_start(argp, format);
6226 	(void) vfprintf(stderr, format, argp);
6227 	va_end(argp);
6228 
6229 	exit(errcode);
6230 }
6231