xref: /titanic_41/usr/src/cmd/cmd-inet/usr.bin/netstat/netstat.c (revision 7b00d7d872f67ffdfbca4cb2abc79157786acb01)
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 2008 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 	boolean_t		first_header = B_TRUE;
2582 
2583 	/* 'for' loop 1: */
2584 	for (; item; item = item->next_item) {
2585 		if (Dflag) {
2586 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
2587 			(void) printf("Group = %d, mib_id = %d, "
2588 			    "length = %d, valp = 0x%p\n",
2589 			    item->group, item->mib_id, item->length,
2590 			    item->valp);
2591 		}
2592 
2593 		switch (item->group) {
2594 		case MIB2_IP:
2595 		if (item->mib_id != MIB2_IP_ADDR ||
2596 		    !family_selected(AF_INET))
2597 			continue; /* 'for' loop 1 */
2598 		{
2599 			static struct ifstat	old = {0L, 0L, 0L, 0L, 0L};
2600 			static struct ifstat	new = {0L, 0L, 0L, 0L, 0L};
2601 			struct ifstat		sum;
2602 			struct iflist		*newlist = NULL;
2603 			static struct iflist	*oldlist = NULL;
2604 			kstat_t	 *ksp;
2605 
2606 			if (once_only) {
2607 				char    ifname[LIFNAMSIZ + 1];
2608 				char    logintname[LIFNAMSIZ + 1];
2609 				mib2_ipAddrEntry_t *ap;
2610 				struct ifstat	stat = {0L, 0L, 0L, 0L, 0L};
2611 				boolean_t	first = B_TRUE;
2612 				uint32_t	new_ifindex;
2613 
2614 				if (Dflag)
2615 					(void) printf("if_report: %d items\n",
2616 					    (item->length)
2617 					    / sizeof (mib2_ipAddrEntry_t));
2618 
2619 				/* 'for' loop 2a: */
2620 				for (ap = (mib2_ipAddrEntry_t *)item->valp;
2621 				    (char *)ap < (char *)item->valp
2622 				    + item->length;
2623 				    ap++) {
2624 					(void) octetstr(&ap->ipAdEntIfIndex,
2625 					    'a', logintname,
2626 					    sizeof (logintname));
2627 					(void) strcpy(ifname, logintname);
2628 					(void) strtok(ifname, ":");
2629 					if (matchname != NULL &&
2630 					    strcmp(matchname, ifname) != 0 &&
2631 					    strcmp(matchname, logintname) != 0)
2632 						continue; /* 'for' loop 2a */
2633 					new_ifindex =
2634 					    if_nametoindex(logintname);
2635 					/*
2636 					 * First lookup the "link" kstats in
2637 					 * case the link is renamed. Then
2638 					 * fallback to the legacy kstats for
2639 					 * those non-GLDv3 links.
2640 					 */
2641 					if (new_ifindex != ifindex_v4 &&
2642 					    (((ksp = kstat_lookup(kc, "link", 0,
2643 					    ifname)) != NULL) ||
2644 					    ((ksp = kstat_lookup(kc, NULL, -1,
2645 					    ifname)) != NULL))) {
2646 						(void) safe_kstat_read(kc, ksp,
2647 						    NULL);
2648 						stat.ipackets =
2649 						    kstat_named_value(ksp,
2650 						    "ipackets");
2651 						stat.ierrors =
2652 						    kstat_named_value(ksp,
2653 						    "ierrors");
2654 						stat.opackets =
2655 						    kstat_named_value(ksp,
2656 						    "opackets");
2657 						stat.oerrors =
2658 						    kstat_named_value(ksp,
2659 						    "oerrors");
2660 						stat.collisions =
2661 						    kstat_named_value(ksp,
2662 						    "collisions");
2663 						if (first) {
2664 							if (!first_header)
2665 							(void) putchar('\n');
2666 							first_header = B_FALSE;
2667 						(void) printf(
2668 						    "%-5.5s %-5.5s%-13.13s "
2669 						    "%-14.14s %-6.6s %-5.5s "
2670 						    "%-6.6s %-5.5s %-6.6s "
2671 						    "%-6.6s\n",
2672 						    "Name", "Mtu", "Net/Dest",
2673 						    "Address", "Ipkts",
2674 						    "Ierrs", "Opkts", "Oerrs",
2675 						    "Collis", "Queue");
2676 
2677 						    first = B_FALSE;
2678 						}
2679 						if_report_ip4(ap, ifname,
2680 						    logintname, &stat, B_TRUE);
2681 						ifindex_v4 = new_ifindex;
2682 					} else {
2683 						if_report_ip4(ap, ifname,
2684 						    logintname, &stat, B_FALSE);
2685 					}
2686 				} /* 'for' loop 2a ends */
2687 			} else if (!alreadydone) {
2688 				char    ifname[LIFNAMSIZ + 1];
2689 				char    buf[LIFNAMSIZ + 1];
2690 				mib2_ipAddrEntry_t *ap;
2691 				struct ifstat   t;
2692 				struct iflist	*tlp = NULL;
2693 				struct iflist	**nextnew = &newlist;
2694 				struct iflist	*walkold;
2695 				struct iflist	*cleanlist;
2696 				boolean_t	found_if = B_FALSE;
2697 
2698 				alreadydone = B_TRUE; /* ignore other case */
2699 
2700 				/*
2701 				 * Check if there is anything to do.
2702 				 */
2703 				if (item->length <
2704 				    sizeof (mib2_ipAddrEntry_t)) {
2705 					fail(0, "No compatible interfaces");
2706 				}
2707 
2708 				/*
2709 				 * 'for' loop 2b: find the "right" entry:
2710 				 * If an interface name to match has been
2711 				 * supplied then try and find it, otherwise
2712 				 * match the first non-loopback interface found.
2713 				 * Use lo0 if all else fails.
2714 				 */
2715 				for (ap = (mib2_ipAddrEntry_t *)item->valp;
2716 				    (char *)ap < (char *)item->valp
2717 				    + item->length;
2718 				    ap++) {
2719 					(void) octetstr(&ap->ipAdEntIfIndex,
2720 					'a', ifname, sizeof (ifname));
2721 					(void) strtok(ifname, ":");
2722 
2723 					if (matchname) {
2724 						if (strcmp(matchname,
2725 						    ifname) == 0) {
2726 							/* 'for' loop 2b */
2727 							found_if = B_TRUE;
2728 							break;
2729 						}
2730 					} else if (strcmp(ifname, "lo0") != 0)
2731 						break; /* 'for' loop 2b */
2732 				} /* 'for' loop 2b ends */
2733 
2734 				if (matchname == NULL) {
2735 					matchname = ifname;
2736 				} else {
2737 					if (!found_if)
2738 						fail(0, "-I: %s no such "
2739 						    "interface.", matchname);
2740 				}
2741 
2742 				if (Iflag_only == 0 || !reentry) {
2743 					(void) printf("    input   %-6.6s    "
2744 					    "output	",
2745 					    matchname);
2746 					(void) printf("   input  (Total)    "
2747 					"output\n");
2748 					(void) printf("%-7.7s %-5.5s %-7.7s "
2749 					    "%-5.5s %-6.6s ",
2750 					    "packets", "errs", "packets",
2751 					    "errs", "colls");
2752 					(void) printf("%-7.7s %-5.5s %-7.7s "
2753 					    "%-5.5s %-6.6s\n",
2754 					    "packets", "errs", "packets",
2755 					    "errs", "colls");
2756 				}
2757 
2758 				sum = zerostat;
2759 
2760 				/* 'for' loop 2c: */
2761 				for (ap = (mib2_ipAddrEntry_t *)item->valp;
2762 				    (char *)ap < (char *)item->valp
2763 				    + item->length;
2764 				    ap++) {
2765 					(void) octetstr(&ap->ipAdEntIfIndex,
2766 					    'a', buf, sizeof (buf));
2767 					(void) strtok(buf, ":");
2768 
2769 					/*
2770 					 * We have reduced the IP interface
2771 					 * name, which could have been a
2772 					 * logical, down to a name suitable
2773 					 * for use with kstats.
2774 					 * We treat this name as unique and
2775 					 * only collate statistics for it once
2776 					 * per pass. This is to avoid falsely
2777 					 * amplifying these statistics by the
2778 					 * the number of logical instances.
2779 					 */
2780 					if ((tlp != NULL) &&
2781 					    ((strcmp(buf, tlp->ifname) == 0))) {
2782 						continue;
2783 					}
2784 
2785 					/*
2786 					 * First lookup the "link" kstats in
2787 					 * case the link is renamed. Then
2788 					 * fallback to the legacy kstats for
2789 					 * those non-GLDv3 links.
2790 					 */
2791 					if (((ksp = kstat_lookup(kc, "link",
2792 					    0, buf)) != NULL ||
2793 					    (ksp = kstat_lookup(kc, NULL, -1,
2794 					    buf)) != NULL) && (ksp->ks_type ==
2795 					    KSTAT_TYPE_NAMED)) {
2796 						(void) safe_kstat_read(kc, ksp,
2797 						    NULL);
2798 					}
2799 
2800 					t.ipackets = kstat_named_value(ksp,
2801 					    "ipackets");
2802 					t.ierrors = kstat_named_value(ksp,
2803 					    "ierrors");
2804 					t.opackets = kstat_named_value(ksp,
2805 					    "opackets");
2806 					t.oerrors = kstat_named_value(ksp,
2807 					    "oerrors");
2808 					t.collisions = kstat_named_value(ksp,
2809 					    "collisions");
2810 
2811 					if (strcmp(buf, matchname) == 0)
2812 						new = t;
2813 
2814 					/* Build the interface list */
2815 
2816 					tlp = malloc(sizeof (struct iflist));
2817 					(void) strlcpy(tlp->ifname, buf,
2818 					    sizeof (tlp->ifname));
2819 					tlp->tot = t;
2820 					*nextnew = tlp;
2821 					nextnew = &tlp->next_if;
2822 
2823 					/*
2824 					 * First time through.
2825 					 * Just add up the interface stats.
2826 					 */
2827 
2828 					if (oldlist == NULL) {
2829 						if_stat_total(&zerostat,
2830 						    &t, &sum);
2831 						continue;
2832 					}
2833 
2834 					/*
2835 					 * Walk old list for the interface.
2836 					 *
2837 					 * If found, add difference to total.
2838 					 *
2839 					 * If not, an interface has been plumbed
2840 					 * up.  In this case, we will simply
2841 					 * ignore the new interface until the
2842 					 * next interval; as there's no easy way
2843 					 * to acquire statistics between time
2844 					 * of the plumb and the next interval
2845 					 * boundary.  This results in inaccurate
2846 					 * total values for current interval.
2847 					 *
2848 					 * Note the case when an interface is
2849 					 * unplumbed; as similar problems exist.
2850 					 * The unplumbed interface is not in the
2851 					 * current list, and there's no easy way
2852 					 * to account for the statistics between
2853 					 * the previous interval and time of the
2854 					 * unplumb.  Therefore, we (in a sense)
2855 					 * ignore the removed interface by only
2856 					 * involving "current" interfaces when
2857 					 * computing the total statistics.
2858 					 * Unfortunately, this also results in
2859 					 * inaccurate values for interval total.
2860 					 */
2861 
2862 					for (walkold = oldlist;
2863 					    walkold != NULL;
2864 					    walkold = walkold->next_if) {
2865 						if (strcmp(walkold->ifname,
2866 						    buf) == 0) {
2867 							if_stat_total(
2868 							    &walkold->tot,
2869 							    &t, &sum);
2870 							break;
2871 						}
2872 					}
2873 
2874 				} /* 'for' loop 2c ends */
2875 
2876 				*nextnew = NULL;
2877 
2878 				(void) printf("%-7llu %-5llu %-7llu "
2879 				    "%-5llu %-6llu ",
2880 				    new.ipackets - old.ipackets,
2881 				    new.ierrors - old.ierrors,
2882 				    new.opackets - old.opackets,
2883 				    new.oerrors - old.oerrors,
2884 				    new.collisions - old.collisions);
2885 
2886 				(void) printf("%-7llu %-5llu %-7llu "
2887 				    "%-5llu %-6llu\n", sum.ipackets,
2888 				    sum.ierrors, sum.opackets,
2889 				    sum.oerrors, sum.collisions);
2890 
2891 				/*
2892 				 * Tidy things up once finished.
2893 				 */
2894 
2895 				old = new;
2896 				cleanlist = oldlist;
2897 				oldlist = newlist;
2898 				while (cleanlist != NULL) {
2899 					tlp = cleanlist->next_if;
2900 					free(cleanlist);
2901 					cleanlist = tlp;
2902 				}
2903 			}
2904 			break;
2905 		}
2906 		case MIB2_IP6:
2907 		if (item->mib_id != MIB2_IP6_ADDR ||
2908 		    !family_selected(AF_INET6))
2909 			continue; /* 'for' loop 1 */
2910 		{
2911 			static struct ifstat	old6 = {0L, 0L, 0L, 0L, 0L};
2912 			static struct ifstat	new6 = {0L, 0L, 0L, 0L, 0L};
2913 			struct ifstat		sum6;
2914 			struct iflist		*newlist6 = NULL;
2915 			static struct iflist	*oldlist6 = NULL;
2916 			kstat_t	 *ksp;
2917 
2918 			if (once_only) {
2919 				char    ifname[LIFNAMSIZ + 1];
2920 				char    logintname[LIFNAMSIZ + 1];
2921 				mib2_ipv6AddrEntry_t *ap6;
2922 				struct ifstat	stat = {0L, 0L, 0L, 0L, 0L};
2923 				boolean_t	first = B_TRUE;
2924 				uint32_t	new_ifindex;
2925 
2926 				if (Dflag)
2927 					(void) printf("if_report: %d items\n",
2928 					    (item->length)
2929 					    / sizeof (mib2_ipv6AddrEntry_t));
2930 				/* 'for' loop 2d: */
2931 				for (ap6 = (mib2_ipv6AddrEntry_t *)item->valp;
2932 				    (char *)ap6 < (char *)item->valp
2933 				    + item->length;
2934 				    ap6++) {
2935 					(void) octetstr(&ap6->ipv6AddrIfIndex,
2936 					    'a', logintname,
2937 					    sizeof (logintname));
2938 					(void) strcpy(ifname, logintname);
2939 					(void) strtok(ifname, ":");
2940 					if (matchname != NULL &&
2941 					    strcmp(matchname, ifname) != 0 &&
2942 					    strcmp(matchname, logintname) != 0)
2943 						continue; /* 'for' loop 2d */
2944 					new_ifindex =
2945 					    if_nametoindex(logintname);
2946 
2947 					/*
2948 					 * First lookup the "link" kstats in
2949 					 * case the link is renamed. Then
2950 					 * fallback to the legacy kstats for
2951 					 * those non-GLDv3 links.
2952 					 */
2953 					if (new_ifindex != ifindex_v6 &&
2954 					    ((ksp = kstat_lookup(kc, "link", 0,
2955 					    ifname)) != NULL ||
2956 					    (ksp = kstat_lookup(kc, NULL, -1,
2957 					    ifname)) != NULL)) {
2958 						(void) safe_kstat_read(kc, ksp,
2959 						    NULL);
2960 						stat.ipackets =
2961 						    kstat_named_value(ksp,
2962 						    "ipackets");
2963 						stat.ierrors =
2964 						    kstat_named_value(ksp,
2965 						    "ierrors");
2966 						stat.opackets =
2967 						    kstat_named_value(ksp,
2968 						    "opackets");
2969 						stat.oerrors =
2970 						    kstat_named_value(ksp,
2971 						    "oerrors");
2972 						stat.collisions =
2973 						    kstat_named_value(ksp,
2974 						    "collisions");
2975 						if (first) {
2976 							if (!first_header)
2977 							(void) putchar('\n');
2978 							first_header = B_FALSE;
2979 							(void) printf(
2980 							    "%-5.5s %-5.5s%"
2981 							    "-27.27s %-27.27s "
2982 							    "%-6.6s %-5.5s "
2983 							    "%-6.6s %-5.5s "
2984 							    "%-6.6s\n",
2985 							    "Name", "Mtu",
2986 							    "Net/Dest",
2987 							    "Address", "Ipkts",
2988 							    "Ierrs", "Opkts",
2989 							    "Oerrs", "Collis");
2990 							first = B_FALSE;
2991 						}
2992 						if_report_ip6(ap6, ifname,
2993 						    logintname, &stat, B_TRUE);
2994 						ifindex_v6 = new_ifindex;
2995 					} else {
2996 						if_report_ip6(ap6, ifname,
2997 						    logintname, &stat, B_FALSE);
2998 					}
2999 				} /* 'for' loop 2d ends */
3000 			} else if (!alreadydone) {
3001 				char    ifname[LIFNAMSIZ + 1];
3002 				char    buf[IFNAMSIZ + 1];
3003 				mib2_ipv6AddrEntry_t *ap6;
3004 				struct ifstat   t;
3005 				struct iflist	*tlp = NULL;
3006 				struct iflist	**nextnew = &newlist6;
3007 				struct iflist	*walkold;
3008 				struct iflist	*cleanlist;
3009 				boolean_t	found_if = B_FALSE;
3010 
3011 				alreadydone = B_TRUE; /* ignore other case */
3012 
3013 				/*
3014 				 * Check if there is anything to do.
3015 				 */
3016 				if (item->length <
3017 				    sizeof (mib2_ipv6AddrEntry_t)) {
3018 					fail(0, "No compatible interfaces");
3019 				}
3020 
3021 				/*
3022 				 * 'for' loop 2e: find the "right" entry:
3023 				 * If an interface name to match has been
3024 				 * supplied then try and find it, otherwise
3025 				 * match the first non-loopback interface found.
3026 				 * Use lo0 if all else fails.
3027 				 */
3028 				for (ap6 = (mib2_ipv6AddrEntry_t *)item->valp;
3029 				    (char *)ap6 < (char *)item->valp
3030 				    + item->length;
3031 				    ap6++) {
3032 					(void) octetstr(&ap6->ipv6AddrIfIndex,
3033 					    'a', ifname, sizeof (ifname));
3034 					(void) strtok(ifname, ":");
3035 
3036 					if (matchname) {
3037 						if (strcmp(matchname,
3038 						    ifname) == 0) {
3039 							/* 'for' loop 2e */
3040 							found_if = B_TRUE;
3041 							break;
3042 						}
3043 					} else if (strcmp(ifname, "lo0") != 0)
3044 						break; /* 'for' loop 2e */
3045 				} /* 'for' loop 2e ends */
3046 
3047 				if (matchname == NULL) {
3048 					matchname = ifname;
3049 				} else {
3050 					if (!found_if)
3051 						fail(0, "-I: %s no such "
3052 						    "interface.", matchname);
3053 				}
3054 
3055 				if (Iflag_only == 0 || !reentry) {
3056 					(void) printf(
3057 					    "    input   %-6.6s"
3058 					    "    output	",
3059 					    matchname);
3060 					(void) printf("   input  (Total)"
3061 					    "    output\n");
3062 					(void) printf("%-7.7s %-5.5s %-7.7s "
3063 					    "%-5.5s %-6.6s ",
3064 					    "packets", "errs", "packets",
3065 					    "errs", "colls");
3066 					(void) printf("%-7.7s %-5.5s %-7.7s "
3067 					    "%-5.5s %-6.6s\n",
3068 					    "packets", "errs", "packets",
3069 					    "errs", "colls");
3070 				}
3071 
3072 				sum6 = zerostat;
3073 
3074 				/* 'for' loop 2f: */
3075 				for (ap6 = (mib2_ipv6AddrEntry_t *)item->valp;
3076 				    (char *)ap6 < (char *)item->valp
3077 				    + item->length;
3078 				    ap6++) {
3079 					(void) octetstr(&ap6->ipv6AddrIfIndex,
3080 					    'a', buf, sizeof (buf));
3081 					(void) strtok(buf, ":");
3082 
3083 					/*
3084 					 * We have reduced the IP interface
3085 					 * name, which could have been a
3086 					 * logical, down to a name suitable
3087 					 * for use with kstats.
3088 					 * We treat this name as unique and
3089 					 * only collate statistics for it once
3090 					 * per pass. This is to avoid falsely
3091 					 * amplifying these statistics by the
3092 					 * the number of logical instances.
3093 					 */
3094 
3095 					if ((tlp != NULL) &&
3096 					    ((strcmp(buf, tlp->ifname) == 0))) {
3097 						continue;
3098 					}
3099 
3100 					/*
3101 					 * First lookup the "link" kstats in
3102 					 * case the link is renamed. Then
3103 					 * fallback to the legacy kstats for
3104 					 * those non-GLDv3 links.
3105 					 */
3106 					if (((ksp = kstat_lookup(kc, "link",
3107 					    0, buf)) != NULL ||
3108 					    (ksp = kstat_lookup(kc, NULL, -1,
3109 					    buf)) != NULL) && (ksp->ks_type ==
3110 					    KSTAT_TYPE_NAMED)) {
3111 						(void) safe_kstat_read(kc,
3112 						    ksp, NULL);
3113 					}
3114 
3115 					t.ipackets = kstat_named_value(ksp,
3116 					    "ipackets");
3117 					t.ierrors = kstat_named_value(ksp,
3118 					    "ierrors");
3119 					t.opackets = kstat_named_value(ksp,
3120 					    "opackets");
3121 					t.oerrors = kstat_named_value(ksp,
3122 					    "oerrors");
3123 					t.collisions = kstat_named_value(ksp,
3124 					    "collisions");
3125 
3126 					if (strcmp(buf, matchname) == 0)
3127 						new6 = t;
3128 
3129 					/* Build the interface list */
3130 
3131 					tlp = malloc(sizeof (struct iflist));
3132 					(void) strlcpy(tlp->ifname, buf,
3133 					    sizeof (tlp->ifname));
3134 					tlp->tot = t;
3135 					*nextnew = tlp;
3136 					nextnew = &tlp->next_if;
3137 
3138 					/*
3139 					 * First time through.
3140 					 * Just add up the interface stats.
3141 					 */
3142 
3143 					if (oldlist6 == NULL) {
3144 						if_stat_total(&zerostat,
3145 						    &t, &sum6);
3146 						continue;
3147 					}
3148 
3149 					/*
3150 					 * Walk old list for the interface.
3151 					 *
3152 					 * If found, add difference to total.
3153 					 *
3154 					 * If not, an interface has been plumbed
3155 					 * up.  In this case, we will simply
3156 					 * ignore the new interface until the
3157 					 * next interval; as there's no easy way
3158 					 * to acquire statistics between time
3159 					 * of the plumb and the next interval
3160 					 * boundary.  This results in inaccurate
3161 					 * total values for current interval.
3162 					 *
3163 					 * Note the case when an interface is
3164 					 * unplumbed; as similar problems exist.
3165 					 * The unplumbed interface is not in the
3166 					 * current list, and there's no easy way
3167 					 * to account for the statistics between
3168 					 * the previous interval and time of the
3169 					 * unplumb.  Therefore, we (in a sense)
3170 					 * ignore the removed interface by only
3171 					 * involving "current" interfaces when
3172 					 * computing the total statistics.
3173 					 * Unfortunately, this also results in
3174 					 * inaccurate values for interval total.
3175 					 */
3176 
3177 					for (walkold = oldlist6;
3178 					    walkold != NULL;
3179 					    walkold = walkold->next_if) {
3180 						if (strcmp(walkold->ifname,
3181 						    buf) == 0) {
3182 							if_stat_total(
3183 							    &walkold->tot,
3184 							    &t, &sum6);
3185 							break;
3186 						}
3187 					}
3188 
3189 				} /* 'for' loop 2f ends */
3190 
3191 				*nextnew = NULL;
3192 
3193 				(void) printf("%-7llu %-5llu %-7llu "
3194 				    "%-5llu %-6llu ",
3195 				    new6.ipackets - old6.ipackets,
3196 				    new6.ierrors - old6.ierrors,
3197 				    new6.opackets - old6.opackets,
3198 				    new6.oerrors - old6.oerrors,
3199 				    new6.collisions - old6.collisions);
3200 
3201 				(void) printf("%-7llu %-5llu %-7llu "
3202 				    "%-5llu %-6llu\n", sum6.ipackets,
3203 				    sum6.ierrors, sum6.opackets,
3204 				    sum6.oerrors, sum6.collisions);
3205 
3206 				/*
3207 				 * Tidy things up once finished.
3208 				 */
3209 
3210 				old6 = new6;
3211 				cleanlist = oldlist6;
3212 				oldlist6 = newlist6;
3213 				while (cleanlist != NULL) {
3214 					tlp = cleanlist->next_if;
3215 					free(cleanlist);
3216 					cleanlist = tlp;
3217 				}
3218 			}
3219 			break;
3220 		}
3221 		}
3222 		(void) fflush(stdout);
3223 	} /* 'for' loop 1 ends */
3224 	if ((Iflag_only == 0) && (!once_only))
3225 		(void) putchar('\n');
3226 	reentry = B_TRUE;
3227 }
3228 
3229 static void
3230 if_report_ip4(mib2_ipAddrEntry_t *ap,
3231 	char ifname[], char logintname[], struct ifstat *statptr,
3232 	boolean_t ksp_not_null) {
3233 
3234 	char abuf[MAXHOSTNAMELEN + 1];
3235 	char dstbuf[MAXHOSTNAMELEN + 1];
3236 
3237 	if (ksp_not_null) {
3238 		(void) printf("%-5s %-5u",
3239 		    ifname, ap->ipAdEntInfo.ae_mtu);
3240 		if (ap->ipAdEntInfo.ae_flags & IFF_POINTOPOINT)
3241 			(void) pr_addr(ap->ipAdEntInfo.ae_pp_dst_addr,
3242 			    abuf, sizeof (abuf));
3243 		else
3244 			(void) pr_netaddr(ap->ipAdEntAddr,
3245 			    ap->ipAdEntNetMask, abuf, sizeof (abuf));
3246 		(void) printf("%-13s %-14s %-6llu %-5llu %-6llu %-5llu "
3247 		    "%-6llu %-6llu\n",
3248 		    abuf, pr_addr(ap->ipAdEntAddr, dstbuf, sizeof (dstbuf)),
3249 		    statptr->ipackets, statptr->ierrors,
3250 		    statptr->opackets, statptr->oerrors,
3251 		    statptr->collisions, 0LL);
3252 	}
3253 	/*
3254 	 * Print logical interface info if Aflag set (including logical unit 0)
3255 	 */
3256 	if (Aflag) {
3257 		*statptr = zerostat;
3258 		statptr->ipackets = ap->ipAdEntInfo.ae_ibcnt;
3259 		statptr->opackets = ap->ipAdEntInfo.ae_obcnt;
3260 
3261 		(void) printf("%-5s %-5u", logintname, ap->ipAdEntInfo.ae_mtu);
3262 		if (ap->ipAdEntInfo.ae_flags & IFF_POINTOPOINT)
3263 			(void) pr_addr(ap->ipAdEntInfo.ae_pp_dst_addr, abuf,
3264 			sizeof (abuf));
3265 		else
3266 			(void) pr_netaddr(ap->ipAdEntAddr, ap->ipAdEntNetMask,
3267 			    abuf, sizeof (abuf));
3268 
3269 		(void) printf("%-13s %-14s %-6llu %-5s %-6llu "
3270 		    "%-5s %-6s %-6llu\n", abuf,
3271 		    pr_addr(ap->ipAdEntAddr, dstbuf, sizeof (dstbuf)),
3272 		    statptr->ipackets, "N/A", statptr->opackets, "N/A", "N/A",
3273 		    0LL);
3274 	}
3275 }
3276 
3277 static void
3278 if_report_ip6(mib2_ipv6AddrEntry_t *ap6,
3279 	char ifname[], char logintname[], struct ifstat *statptr,
3280 	boolean_t ksp_not_null) {
3281 
3282 	char abuf[MAXHOSTNAMELEN + 1];
3283 	char dstbuf[MAXHOSTNAMELEN + 1];
3284 
3285 	if (ksp_not_null) {
3286 		(void) printf("%-5s %-5u", ifname, ap6->ipv6AddrInfo.ae_mtu);
3287 		if (ap6->ipv6AddrInfo.ae_flags &
3288 		    IFF_POINTOPOINT) {
3289 			(void) pr_addr6(&ap6->ipv6AddrInfo.ae_pp_dst_addr,
3290 			    abuf, sizeof (abuf));
3291 		} else {
3292 			(void) pr_prefix6(&ap6->ipv6AddrAddress,
3293 			    ap6->ipv6AddrPfxLength, abuf,
3294 			    sizeof (abuf));
3295 		}
3296 		(void) printf("%-27s %-27s %-6llu %-5llu "
3297 		    "%-6llu %-5llu %-6llu\n",
3298 		    abuf, pr_addr6(&ap6->ipv6AddrAddress, dstbuf,
3299 		    sizeof (dstbuf)),
3300 		    statptr->ipackets, statptr->ierrors, statptr->opackets,
3301 		    statptr->oerrors, statptr->collisions);
3302 	}
3303 	/*
3304 	 * Print logical interface info if Aflag set (including logical unit 0)
3305 	 */
3306 	if (Aflag) {
3307 		*statptr = zerostat;
3308 		statptr->ipackets = ap6->ipv6AddrInfo.ae_ibcnt;
3309 		statptr->opackets = ap6->ipv6AddrInfo.ae_obcnt;
3310 
3311 		(void) printf("%-5s %-5u", logintname,
3312 		    ap6->ipv6AddrInfo.ae_mtu);
3313 		if (ap6->ipv6AddrInfo.ae_flags & IFF_POINTOPOINT)
3314 			(void) pr_addr6(&ap6->ipv6AddrInfo.ae_pp_dst_addr,
3315 			    abuf, sizeof (abuf));
3316 		else
3317 			(void) pr_prefix6(&ap6->ipv6AddrAddress,
3318 			    ap6->ipv6AddrPfxLength, abuf, sizeof (abuf));
3319 		(void) printf("%-27s %-27s %-6llu %-5s %-6llu %-5s %-6s\n",
3320 		    abuf, pr_addr6(&ap6->ipv6AddrAddress, dstbuf,
3321 		    sizeof (dstbuf)),
3322 		    statptr->ipackets, "N/A",
3323 		    statptr->opackets, "N/A", "N/A");
3324 	}
3325 }
3326 
3327 /* --------------------- DHCP_REPORT  (netstat -D) ------------------------- */
3328 
3329 static boolean_t
3330 dhcp_do_ipc(dhcp_ipc_type_t type, const char *ifname, boolean_t printed_one)
3331 {
3332 	dhcp_ipc_request_t	*request;
3333 	dhcp_ipc_reply_t	*reply;
3334 	int			error;
3335 
3336 	request = dhcp_ipc_alloc_request(type, ifname, NULL, 0, DHCP_TYPE_NONE);
3337 	if (request == NULL)
3338 		fail(0, "dhcp_do_ipc: out of memory");
3339 
3340 	error = dhcp_ipc_make_request(request, &reply, DHCP_IPC_WAIT_DEFAULT);
3341 	if (error != 0) {
3342 		free(request);
3343 		fail(0, "dhcp_do_ipc: %s", dhcp_ipc_strerror(error));
3344 	}
3345 
3346 	free(request);
3347 	error = reply->return_code;
3348 	if (error == DHCP_IPC_E_UNKIF) {
3349 		free(reply);
3350 		return (printed_one);
3351 	}
3352 	if (error != 0) {
3353 		free(reply);
3354 		fail(0, "dhcp_do_ipc: %s", dhcp_ipc_strerror(error));
3355 	}
3356 
3357 	if (!printed_one)
3358 		(void) printf("%s", dhcp_status_hdr_string());
3359 
3360 	(void) printf("%s", dhcp_status_reply_to_string(reply));
3361 	free(reply);
3362 	return (B_TRUE);
3363 }
3364 
3365 /*
3366  * dhcp_walk_interfaces: walk the list of interfaces that have a given set of
3367  * flags turned on (flags_on) and a given set turned off (flags_off) for a
3368  * given address family (af).  For each, print out the DHCP status using
3369  * dhcp_do_ipc.
3370  */
3371 static boolean_t
3372 dhcp_walk_interfaces(uint_t flags_on, uint_t flags_off, int af,
3373     boolean_t printed_one)
3374 {
3375 	struct lifnum	lifn;
3376 	struct lifconf	lifc;
3377 	int		n_ifs, i, sock_fd;
3378 
3379 	sock_fd = socket(af, SOCK_DGRAM, 0);
3380 	if (sock_fd == -1)
3381 		return (printed_one);
3382 
3383 	/*
3384 	 * SIOCGLIFNUM is just an estimate.  If the ioctl fails, we don't care;
3385 	 * just drive on and use SIOCGLIFCONF with increasing buffer sizes, as
3386 	 * is traditional.
3387 	 */
3388 	(void) memset(&lifn, 0, sizeof (lifn));
3389 	lifn.lifn_family = af;
3390 	lifn.lifn_flags = LIFC_ALLZONES | LIFC_NOXMIT;
3391 	if (ioctl(sock_fd, SIOCGLIFNUM, &lifn) == -1)
3392 		n_ifs = LIFN_GUARD_VALUE;
3393 	else
3394 		n_ifs = lifn.lifn_count + LIFN_GUARD_VALUE;
3395 
3396 	(void) memset(&lifc, 0, sizeof (lifc));
3397 	lifc.lifc_family = af;
3398 	lifc.lifc_flags = lifn.lifn_flags;
3399 	lifc.lifc_len = n_ifs * sizeof (struct lifreq);
3400 	lifc.lifc_buf = malloc(lifc.lifc_len);
3401 	if (lifc.lifc_buf != NULL) {
3402 
3403 		if (ioctl(sock_fd, SIOCGLIFCONF, &lifc) == -1) {
3404 			(void) close(sock_fd);
3405 			free(lifc.lifc_buf);
3406 			return (NULL);
3407 		}
3408 
3409 		n_ifs = lifc.lifc_len / sizeof (struct lifreq);
3410 
3411 		for (i = 0; i < n_ifs; i++) {
3412 			if (ioctl(sock_fd, SIOCGLIFFLAGS, &lifc.lifc_req[i]) ==
3413 			    0 && (lifc.lifc_req[i].lifr_flags & (flags_on |
3414 			    flags_off)) != flags_on)
3415 				continue;
3416 			printed_one = dhcp_do_ipc(DHCP_STATUS |
3417 			    (af == AF_INET6 ? DHCP_V6 : 0),
3418 			    lifc.lifc_req[i].lifr_name, printed_one);
3419 		}
3420 	}
3421 	(void) close(sock_fd);
3422 	free(lifc.lifc_buf);
3423 	return (printed_one);
3424 }
3425 
3426 static void
3427 dhcp_report(char *ifname)
3428 {
3429 	boolean_t printed_one;
3430 
3431 	if (!family_selected(AF_INET) && !family_selected(AF_INET6))
3432 		return;
3433 
3434 	printed_one = B_FALSE;
3435 	if (ifname != NULL) {
3436 		if (family_selected(AF_INET)) {
3437 			printed_one = dhcp_do_ipc(DHCP_STATUS, ifname,
3438 			    printed_one);
3439 		}
3440 		if (family_selected(AF_INET6)) {
3441 			printed_one = dhcp_do_ipc(DHCP_STATUS | DHCP_V6,
3442 			    ifname, printed_one);
3443 		}
3444 		if (!printed_one) {
3445 			fail(0, "%s: %s", ifname,
3446 			    dhcp_ipc_strerror(DHCP_IPC_E_UNKIF));
3447 		}
3448 	} else {
3449 		if (family_selected(AF_INET)) {
3450 			printed_one = dhcp_walk_interfaces(IFF_DHCPRUNNING,
3451 			    0, AF_INET, printed_one);
3452 		}
3453 		if (family_selected(AF_INET6)) {
3454 			(void) dhcp_walk_interfaces(IFF_DHCPRUNNING,
3455 			    IFF_ADDRCONF, AF_INET6, printed_one);
3456 		}
3457 	}
3458 }
3459 
3460 /* --------------------- GROUP_REPORT (netstat -g) ------------------------- */
3461 
3462 static void
3463 group_report(mib_item_t *item)
3464 {
3465 	mib_item_t	*v4grp = NULL, *v4src = NULL;
3466 	mib_item_t	*v6grp = NULL, *v6src = NULL;
3467 	int		jtemp = 0;
3468 	char		ifname[LIFNAMSIZ + 1];
3469 	char		abuf[MAXHOSTNAMELEN + 1];
3470 	ip_member_t	*ipmp;
3471 	ip_grpsrc_t	*ips;
3472 	ipv6_member_t	*ipmp6;
3473 	ipv6_grpsrc_t	*ips6;
3474 	char		*ifnamep;
3475 	boolean_t	first, first_src;
3476 
3477 	/* 'for' loop 1: */
3478 	for (; item; item = item->next_item) {
3479 		if (Dflag) {
3480 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3481 			(void) printf("Group = %d, mib_id = %d, "
3482 			    "length = %d, valp = 0x%p\n",
3483 			    item->group, item->mib_id, item->length,
3484 			    item->valp);
3485 		}
3486 		if (item->group == MIB2_IP && family_selected(AF_INET)) {
3487 			switch (item->mib_id) {
3488 			case EXPER_IP_GROUP_MEMBERSHIP:
3489 				v4grp = item;
3490 				if (Dflag)
3491 					(void) printf("item is v4grp info\n");
3492 				break;
3493 			case EXPER_IP_GROUP_SOURCES:
3494 				v4src = item;
3495 				if (Dflag)
3496 					(void) printf("item is v4src info\n");
3497 				break;
3498 			default:
3499 				continue;
3500 			}
3501 			continue;
3502 		}
3503 		if (item->group == MIB2_IP6 && family_selected(AF_INET6)) {
3504 			switch (item->mib_id) {
3505 			case EXPER_IP6_GROUP_MEMBERSHIP:
3506 				v6grp = item;
3507 				if (Dflag)
3508 					(void) printf("item is v6grp info\n");
3509 				break;
3510 			case EXPER_IP6_GROUP_SOURCES:
3511 				v6src = item;
3512 				if (Dflag)
3513 					(void) printf("item is v6src info\n");
3514 				break;
3515 			default:
3516 				continue;
3517 			}
3518 		}
3519 	}
3520 
3521 	if (family_selected(AF_INET) && v4grp != NULL) {
3522 		if (Dflag)
3523 			(void) printf("%u records for ipGroupMember:\n",
3524 			    v4grp->length / sizeof (ip_member_t));
3525 
3526 		first = B_TRUE;
3527 		for (ipmp = (ip_member_t *)v4grp->valp;
3528 		    (char *)ipmp < (char *)v4grp->valp + v4grp->length;
3529 		    /* LINTED: (note 1) */
3530 		    ipmp = (ip_member_t *)((char *)ipmp + ipMemberEntrySize)) {
3531 			if (first) {
3532 				(void) puts(v4compat ?
3533 				    "Group Memberships" :
3534 				    "Group Memberships: IPv4");
3535 				(void) puts("Interface "
3536 				    "Group                RefCnt");
3537 				(void) puts("--------- "
3538 				    "-------------------- ------");
3539 				first = B_FALSE;
3540 			}
3541 
3542 			(void) printf("%-9s %-20s %6u\n",
3543 			    octetstr(&ipmp->ipGroupMemberIfIndex, 'a',
3544 			    ifname, sizeof (ifname)),
3545 			    pr_addr(ipmp->ipGroupMemberAddress,
3546 			    abuf, sizeof (abuf)),
3547 			    ipmp->ipGroupMemberRefCnt);
3548 
3549 
3550 			if (!Vflag || v4src == NULL)
3551 				continue;
3552 
3553 			if (Dflag)
3554 				(void) printf("scanning %u ipGroupSource "
3555 				    "records...\n",
3556 				    v4src->length/sizeof (ip_grpsrc_t));
3557 
3558 			first_src = B_TRUE;
3559 			for (ips = (ip_grpsrc_t *)v4src->valp;
3560 			    (char *)ips < (char *)v4src->valp + v4src->length;
3561 			    /* LINTED: (note 1) */
3562 			    ips = (ip_grpsrc_t *)((char *)ips +
3563 			    ipGroupSourceEntrySize)) {
3564 				/*
3565 				 * We assume that all source addrs for a given
3566 				 * interface/group pair are contiguous, so on
3567 				 * the first non-match after we've found at
3568 				 * least one, we bail.
3569 				 */
3570 				if ((ipmp->ipGroupMemberAddress !=
3571 				    ips->ipGroupSourceGroup) ||
3572 				    (!octetstrmatch(&ipmp->ipGroupMemberIfIndex,
3573 				    &ips->ipGroupSourceIfIndex))) {
3574 					if (first_src)
3575 						continue;
3576 					else
3577 						break;
3578 				}
3579 				if (first_src) {
3580 					(void) printf("\t%s:    %s\n",
3581 					    fmodestr(
3582 					    ipmp->ipGroupMemberFilterMode),
3583 					    pr_addr(ips->ipGroupSourceAddress,
3584 					    abuf, sizeof (abuf)));
3585 					first_src = B_FALSE;
3586 					continue;
3587 				}
3588 
3589 				(void) printf("\t            %s\n",
3590 				    pr_addr(ips->ipGroupSourceAddress, abuf,
3591 				    sizeof (abuf)));
3592 			}
3593 		}
3594 		(void) putchar('\n');
3595 	}
3596 
3597 	if (family_selected(AF_INET6) && v6grp != NULL) {
3598 		if (Dflag)
3599 			(void) printf("%u records for ipv6GroupMember:\n",
3600 			    v6grp->length / sizeof (ipv6_member_t));
3601 
3602 		first = B_TRUE;
3603 		for (ipmp6 = (ipv6_member_t *)v6grp->valp;
3604 		    (char *)ipmp6 < (char *)v6grp->valp + v6grp->length;
3605 		    /* LINTED: (note 1) */
3606 		    ipmp6 = (ipv6_member_t *)((char *)ipmp6 +
3607 			ipv6MemberEntrySize)) {
3608 			if (first) {
3609 				(void) puts("Group Memberships: "
3610 				    "IPv6");
3611 				(void) puts(" If       "
3612 				    "Group                   RefCnt");
3613 				(void) puts("----- "
3614 				    "--------------------------- ------");
3615 				first = B_FALSE;
3616 			}
3617 
3618 			ifnamep = if_indextoname(
3619 			    ipmp6->ipv6GroupMemberIfIndex, ifname);
3620 			if (ifnamep == NULL) {
3621 				(void) printf("Invalid ifindex %d\n",
3622 				    ipmp6->ipv6GroupMemberIfIndex);
3623 				continue;
3624 			}
3625 			(void) printf("%-5s %-27s %5u\n",
3626 			    ifnamep,
3627 			    pr_addr6(&ipmp6->ipv6GroupMemberAddress,
3628 			    abuf, sizeof (abuf)),
3629 			    ipmp6->ipv6GroupMemberRefCnt);
3630 
3631 			if (!Vflag || v6src == NULL)
3632 				continue;
3633 
3634 			if (Dflag)
3635 				(void) printf("scanning %u ipv6GroupSource "
3636 				    "records...\n",
3637 				    v6src->length/sizeof (ipv6_grpsrc_t));
3638 
3639 			first_src = B_TRUE;
3640 			for (ips6 = (ipv6_grpsrc_t *)v6src->valp;
3641 			    (char *)ips6 < (char *)v6src->valp + v6src->length;
3642 			    /* LINTED: (note 1) */
3643 			    ips6 = (ipv6_grpsrc_t *)((char *)ips6 +
3644 			    ipv6GroupSourceEntrySize)) {
3645 				/* same assumption as in the v4 case above */
3646 				if ((ipmp6->ipv6GroupMemberIfIndex !=
3647 				    ips6->ipv6GroupSourceIfIndex) ||
3648 				    (!IN6_ARE_ADDR_EQUAL(
3649 				    &ipmp6->ipv6GroupMemberAddress,
3650 				    &ips6->ipv6GroupSourceGroup))) {
3651 					if (first_src)
3652 						continue;
3653 					else
3654 						break;
3655 				}
3656 				if (first_src) {
3657 					(void) printf("\t%s:    %s\n",
3658 					    fmodestr(
3659 					    ipmp6->ipv6GroupMemberFilterMode),
3660 					    pr_addr6(
3661 					    &ips6->ipv6GroupSourceAddress,
3662 					    abuf, sizeof (abuf)));
3663 					first_src = B_FALSE;
3664 					continue;
3665 				}
3666 
3667 				(void) printf("\t            %s\n",
3668 				    pr_addr6(&ips6->ipv6GroupSourceAddress,
3669 				    abuf, sizeof (abuf)));
3670 			}
3671 		}
3672 		(void) putchar('\n');
3673 	}
3674 
3675 	(void) putchar('\n');
3676 	(void) fflush(stdout);
3677 }
3678 
3679 /* --------------------- ARP_REPORT (netstat -p) -------------------------- */
3680 
3681 static void
3682 arp_report(mib_item_t *item)
3683 {
3684 	int		jtemp = 0;
3685 	char		ifname[LIFNAMSIZ + 1];
3686 	char		abuf[MAXHOSTNAMELEN + 1];
3687 	char		maskbuf[STR_EXPAND * OCTET_LENGTH + 1];
3688 	char		flbuf[32];	/* ACE_F_ flags */
3689 	char		xbuf[STR_EXPAND * OCTET_LENGTH + 1];
3690 	mib2_ipNetToMediaEntry_t	*np;
3691 	int		flags;
3692 	boolean_t	first;
3693 
3694 	if (!(family_selected(AF_INET)))
3695 		return;
3696 
3697 	/* 'for' loop 1: */
3698 	for (; item; item = item->next_item) {
3699 		if (Dflag) {
3700 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3701 			(void) printf("Group = %d, mib_id = %d, "
3702 			    "length = %d, valp = 0x%p\n",
3703 			    item->group, item->mib_id, item->length,
3704 			    item->valp);
3705 		}
3706 		if (!(item->group == MIB2_IP && item->mib_id == MIB2_IP_MEDIA))
3707 			continue; /* 'for' loop 1 */
3708 
3709 		if (Dflag)
3710 			(void) printf("%u records for "
3711 			    "ipNetToMediaEntryTable:\n",
3712 			    item->length/sizeof (mib2_ipNetToMediaEntry_t));
3713 
3714 		first = B_TRUE;
3715 		/* 'for' loop 2: */
3716 		for (np = (mib2_ipNetToMediaEntry_t *)item->valp;
3717 		    (char *)np < (char *)item->valp + item->length;
3718 		    /* LINTED: (note 1) */
3719 		    np = (mib2_ipNetToMediaEntry_t *)((char *)np +
3720 		    ipNetToMediaEntrySize)) {
3721 			if (first) {
3722 				(void) puts(v4compat ?
3723 				    "Net to Media Table" :
3724 				    "Net to Media Table: IPv4");
3725 				(void) puts("Device "
3726 				    "  IP Address               Mask      "
3727 				    "Flags      Phys Addr");
3728 				(void) puts("------ "
3729 				    "-------------------- --------------- "
3730 				    "-------- ---------------");
3731 				first = B_FALSE;
3732 			}
3733 
3734 			flbuf[0] = '\0';
3735 			flags = np->ipNetToMediaInfo.ntm_flags;
3736 			/*
3737 			 * Note that not all flags are possible at the same
3738 			 * time.  Patterns: SPLAy DUo
3739 			 */
3740 			if (flags & ACE_F_PERMANENT)
3741 				(void) strcat(flbuf, "S");
3742 			if (flags & ACE_F_PUBLISH)
3743 				(void) strcat(flbuf, "P");
3744 			if (flags & ACE_F_DYING)
3745 				(void) strcat(flbuf, "D");
3746 			if (!(flags & ACE_F_RESOLVED))
3747 				(void) strcat(flbuf, "U");
3748 			if (flags & ACE_F_MAPPING)
3749 				(void) strcat(flbuf, "M");
3750 			if (flags & ACE_F_MYADDR)
3751 				(void) strcat(flbuf, "L");
3752 			if (flags & ACE_F_UNVERIFIED)
3753 				(void) strcat(flbuf, "d");
3754 			if (flags & ACE_F_AUTHORITY)
3755 				(void) strcat(flbuf, "A");
3756 			if (flags & ACE_F_OLD)
3757 				(void) strcat(flbuf, "o");
3758 			if (flags & ACE_F_DELAYED)
3759 				(void) strcat(flbuf, "y");
3760 			(void) printf("%-6s %-20s %-15s %-8s %s\n",
3761 			    octetstr(&np->ipNetToMediaIfIndex, 'a',
3762 			    ifname, sizeof (ifname)),
3763 			    pr_addr(np->ipNetToMediaNetAddress,
3764 			    abuf, sizeof (abuf)),
3765 			    octetstr(&np->ipNetToMediaInfo.ntm_mask, 'd',
3766 			    maskbuf, sizeof (maskbuf)),
3767 			    flbuf,
3768 			    octetstr(&np->ipNetToMediaPhysAddress, 'h',
3769 			    xbuf, sizeof (xbuf)));
3770 		} /* 'for' loop 2 ends */
3771 	} /* 'for' loop 1 ends */
3772 	(void) fflush(stdout);
3773 }
3774 
3775 /* --------------------- NDP_REPORT (netstat -p) -------------------------- */
3776 
3777 static void
3778 ndp_report(mib_item_t *item)
3779 {
3780 	int		jtemp = 0;
3781 	char		abuf[MAXHOSTNAMELEN + 1];
3782 	char		*state;
3783 	char		*type;
3784 	char		xbuf[STR_EXPAND * OCTET_LENGTH + 1];
3785 	mib2_ipv6NetToMediaEntry_t	*np6;
3786 	char		ifname[LIFNAMSIZ + 1];
3787 	char		*ifnamep;
3788 	boolean_t	first;
3789 
3790 	if (!(family_selected(AF_INET6)))
3791 		return;
3792 
3793 	/* 'for' loop 1: */
3794 	for (; item; item = item->next_item) {
3795 		if (Dflag) {
3796 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3797 			(void) printf("Group = %d, mib_id = %d, "
3798 			    "length = %d, valp = 0x%p\n",
3799 			    item->group, item->mib_id, item->length,
3800 			    item->valp);
3801 		}
3802 		if (!(item->group == MIB2_IP6 &&
3803 		    item->mib_id == MIB2_IP6_MEDIA))
3804 			continue; /* 'for' loop 1 */
3805 
3806 		first = B_TRUE;
3807 		/* 'for' loop 2: */
3808 		for (np6 = (mib2_ipv6NetToMediaEntry_t *)item->valp;
3809 		    (char *)np6 < (char *)item->valp + item->length;
3810 		    /* LINTED: (note 1) */
3811 		    np6 = (mib2_ipv6NetToMediaEntry_t *)((char *)np6 +
3812 		    ipv6NetToMediaEntrySize)) {
3813 			if (first) {
3814 				(void) puts("\nNet to Media Table: IPv6");
3815 				(void) puts(" If   Physical Address   "
3816 				    " Type      State      Destination/Mask");
3817 				(void) puts("----- -----------------  "
3818 				    "------- ------------ "
3819 				    "---------------------------");
3820 				first = B_FALSE;
3821 			}
3822 
3823 			ifnamep = if_indextoname(np6->ipv6NetToMediaIfIndex,
3824 			    ifname);
3825 			if (ifnamep == NULL) {
3826 				(void) printf("Invalid ifindex %d\n",
3827 				    np6->ipv6NetToMediaIfIndex);
3828 				continue; /* 'for' loop 2 */
3829 			}
3830 			switch (np6->ipv6NetToMediaState) {
3831 			case ND_INCOMPLETE:
3832 				state = "INCOMPLETE";
3833 				break;
3834 			case ND_REACHABLE:
3835 				state = "REACHABLE";
3836 				break;
3837 			case ND_STALE:
3838 				state = "STALE";
3839 				break;
3840 			case ND_DELAY:
3841 				state = "DELAY";
3842 				break;
3843 			case ND_PROBE:
3844 				state = "PROBE";
3845 				break;
3846 			case ND_UNREACHABLE:
3847 				state = "UNREACHABLE";
3848 				break;
3849 			default:
3850 				state = "UNKNOWN";
3851 			}
3852 
3853 			switch (np6->ipv6NetToMediaType) {
3854 			case 1:
3855 				type = "other";
3856 				break;
3857 			case 2:
3858 				type = "dynamic";
3859 				break;
3860 			case 3:
3861 				type = "static";
3862 				break;
3863 			case 4:
3864 				type = "local";
3865 				break;
3866 			}
3867 			(void) printf("%-5s %-17s  %-7s %-12s %-27s\n",
3868 			    ifnamep,
3869 			    octetstr(&np6->ipv6NetToMediaPhysAddress, 'h',
3870 			    xbuf, sizeof (xbuf)),
3871 			    type,
3872 			    state,
3873 			    pr_addr6(&np6->ipv6NetToMediaNetAddress,
3874 			    abuf, sizeof (abuf)));
3875 		} /* 'for' loop 2 ends */
3876 	} /* 'for' loop 1 ends */
3877 	(void) putchar('\n');
3878 	(void) fflush(stdout);
3879 }
3880 
3881 /* ------------------------- ire_report (netstat -r) ------------------------ */
3882 
3883 typedef struct sec_attr_list_s {
3884 	struct sec_attr_list_s *sal_next;
3885 	const mib2_ipAttributeEntry_t *sal_attr;
3886 } sec_attr_list_t;
3887 
3888 static boolean_t ire_report_item_v4(const mib2_ipRouteEntry_t *, boolean_t,
3889     const sec_attr_list_t *);
3890 static boolean_t ire_report_item_v6(const mib2_ipv6RouteEntry_t *, boolean_t,
3891     const sec_attr_list_t *);
3892 static const char *pr_secattr(const sec_attr_list_t *);
3893 
3894 static void
3895 ire_report(const mib_item_t *item)
3896 {
3897 	int			jtemp = 0;
3898 	boolean_t		print_hdr_once_v4 = B_TRUE;
3899 	boolean_t		print_hdr_once_v6 = B_TRUE;
3900 	mib2_ipRouteEntry_t	*rp;
3901 	mib2_ipv6RouteEntry_t	*rp6;
3902 	sec_attr_list_t		**v4_attrs, **v4a;
3903 	sec_attr_list_t		**v6_attrs, **v6a;
3904 	sec_attr_list_t		*all_attrs, *aptr;
3905 	const mib_item_t	*iptr;
3906 	int			ipv4_route_count, ipv6_route_count;
3907 	int			route_attrs_count;
3908 
3909 	/*
3910 	 * Preparation pass: the kernel returns separate entries for IP routing
3911 	 * table entries and security attributes.  We loop through the
3912 	 * attributes first and link them into lists.
3913 	 */
3914 	ipv4_route_count = ipv6_route_count = route_attrs_count = 0;
3915 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
3916 		if (iptr->group == MIB2_IP6 && iptr->mib_id == MIB2_IP6_ROUTE)
3917 			ipv6_route_count += iptr->length / ipv6RouteEntrySize;
3918 		if (iptr->group == MIB2_IP && iptr->mib_id == MIB2_IP_ROUTE)
3919 			ipv4_route_count += iptr->length / ipRouteEntrySize;
3920 		if ((iptr->group == MIB2_IP || iptr->group == MIB2_IP6) &&
3921 		    iptr->mib_id == EXPER_IP_RTATTR)
3922 			route_attrs_count += iptr->length /
3923 			    ipRouteAttributeSize;
3924 	}
3925 	v4_attrs = v6_attrs = NULL;
3926 	all_attrs = NULL;
3927 	if (family_selected(AF_INET) && ipv4_route_count > 0) {
3928 		v4_attrs = calloc(ipv4_route_count, sizeof (*v4_attrs));
3929 		if (v4_attrs == NULL) {
3930 			perror("ire_report calloc v4_attrs failed");
3931 			return;
3932 		}
3933 	}
3934 	if (family_selected(AF_INET6) && ipv6_route_count > 0) {
3935 		v6_attrs = calloc(ipv6_route_count, sizeof (*v6_attrs));
3936 		if (v6_attrs == NULL) {
3937 			perror("ire_report calloc v6_attrs failed");
3938 			goto ire_report_done;
3939 		}
3940 	}
3941 	if (route_attrs_count > 0) {
3942 		all_attrs = malloc(route_attrs_count * sizeof (*all_attrs));
3943 		if (all_attrs == NULL) {
3944 			perror("ire_report malloc all_attrs failed");
3945 			goto ire_report_done;
3946 		}
3947 	}
3948 	aptr = all_attrs;
3949 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
3950 		mib2_ipAttributeEntry_t *iae;
3951 		sec_attr_list_t **alp;
3952 
3953 		if (v4_attrs != NULL && iptr->group == MIB2_IP &&
3954 		    iptr->mib_id == EXPER_IP_RTATTR) {
3955 			alp = v4_attrs;
3956 		} else if (v6_attrs != NULL && iptr->group == MIB2_IP6 &&
3957 		    iptr->mib_id == EXPER_IP_RTATTR) {
3958 			alp = v6_attrs;
3959 		} else {
3960 			continue;
3961 		}
3962 		for (iae = iptr->valp;
3963 		    (char *)iae < (char *)iptr->valp + iptr->length;
3964 		    /* LINTED: (note 1) */
3965 		    iae = (mib2_ipAttributeEntry_t *)((char *)iae +
3966 		    ipRouteAttributeSize)) {
3967 			aptr->sal_next = alp[iae->iae_routeidx];
3968 			aptr->sal_attr = iae;
3969 			alp[iae->iae_routeidx] = aptr++;
3970 		}
3971 	}
3972 
3973 	/* 'for' loop 1: */
3974 	v4a = v4_attrs;
3975 	v6a = v6_attrs;
3976 	for (; item != NULL; item = item->next_item) {
3977 		if (Dflag) {
3978 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
3979 			(void) printf("Group = %d, mib_id = %d, "
3980 			    "length = %d, valp = 0x%p\n",
3981 			    item->group, item->mib_id,
3982 			    item->length, item->valp);
3983 		}
3984 		if (!((item->group == MIB2_IP &&
3985 		    item->mib_id == MIB2_IP_ROUTE) ||
3986 		    (item->group == MIB2_IP6 &&
3987 		    item->mib_id == MIB2_IP6_ROUTE)))
3988 			continue; /* 'for' loop 1 */
3989 
3990 		if (item->group == MIB2_IP && !family_selected(AF_INET))
3991 			continue; /* 'for' loop 1 */
3992 		else if (item->group == MIB2_IP6 && !family_selected(AF_INET6))
3993 			continue; /* 'for' loop 1 */
3994 
3995 		if (Dflag) {
3996 			if (item->group == MIB2_IP) {
3997 				(void) printf("%u records for "
3998 				    "ipRouteEntryTable:\n",
3999 				    item->length/sizeof (mib2_ipRouteEntry_t));
4000 			} else {
4001 				(void) printf("%u records for "
4002 				    "ipv6RouteEntryTable:\n",
4003 				    item->length/
4004 				    sizeof (mib2_ipv6RouteEntry_t));
4005 			}
4006 		}
4007 
4008 		if (item->group == MIB2_IP) {
4009 			for (rp = (mib2_ipRouteEntry_t *)item->valp;
4010 			    (char *)rp < (char *)item->valp + item->length;
4011 			    /* LINTED: (note 1) */
4012 			    rp = (mib2_ipRouteEntry_t *)((char *)rp +
4013 			    ipRouteEntrySize)) {
4014 				aptr = v4a == NULL ? NULL : *v4a++;
4015 				print_hdr_once_v4 = ire_report_item_v4(rp,
4016 				    print_hdr_once_v4, aptr);
4017 			}
4018 		} else {
4019 			for (rp6 = (mib2_ipv6RouteEntry_t *)item->valp;
4020 			    (char *)rp6 < (char *)item->valp + item->length;
4021 			    /* LINTED: (note 1) */
4022 			    rp6 = (mib2_ipv6RouteEntry_t *)((char *)rp6 +
4023 			    ipv6RouteEntrySize)) {
4024 				aptr = v6a == NULL ? NULL : *v6a++;
4025 				print_hdr_once_v6 = ire_report_item_v6(rp6,
4026 				    print_hdr_once_v6, aptr);
4027 			}
4028 		}
4029 	} /* 'for' loop 1 ends */
4030 	(void) fflush(stdout);
4031 ire_report_done:
4032 	if (v4_attrs != NULL)
4033 		free(v4_attrs);
4034 	if (v6_attrs != NULL)
4035 		free(v6_attrs);
4036 	if (all_attrs != NULL)
4037 		free(all_attrs);
4038 }
4039 
4040 /*
4041  * Match a user-supplied device name.  We do this by string because
4042  * the MIB2 interface gives us interface name strings rather than
4043  * ifIndex numbers.  The "none" rule matches only routes with no
4044  * interface.  The "any" rule matches routes with any non-blank
4045  * interface.  A base name ("hme0") matches all aliases as well
4046  * ("hme0:1").
4047  */
4048 static boolean_t
4049 dev_name_match(const DeviceName *devnam, const char *ifname)
4050 {
4051 	int iflen;
4052 
4053 	if (ifname == NULL)
4054 		return (devnam->o_length == 0);		/* "none" */
4055 	if (*ifname == '\0')
4056 		return (devnam->o_length != 0);		/* "any" */
4057 	iflen = strlen(ifname);
4058 	/* The check for ':' here supports interface aliases. */
4059 	if (iflen > devnam->o_length ||
4060 	    (iflen < devnam->o_length && devnam->o_bytes[iflen] != ':'))
4061 		return (B_FALSE);
4062 	return (strncmp(ifname, devnam->o_bytes, iflen) == 0);
4063 }
4064 
4065 /*
4066  * Match a user-supplied IP address list.  The "any" rule matches any
4067  * non-zero address.  The "none" rule matches only the zero address.
4068  * IPv6 addresses supplied by the user are ignored.  If the user
4069  * supplies a subnet mask, then match routes that are at least that
4070  * specific (use the user's mask).  If the user supplies only an
4071  * address, then select any routes that would match (use the route's
4072  * mask).
4073  */
4074 static boolean_t
4075 v4_addr_match(IpAddress addr, IpAddress mask, const filter_t *fp)
4076 {
4077 	char **app;
4078 	char *aptr;
4079 	in_addr_t faddr, fmask;
4080 
4081 	if (fp->u.a.f_address == NULL) {
4082 		if (IN6_IS_ADDR_UNSPECIFIED(&fp->u.a.f_mask))
4083 			return (addr != INADDR_ANY);	/* "any" */
4084 		else
4085 			return (addr == INADDR_ANY);	/* "none" */
4086 	}
4087 	if (!IN6_IS_V4MASK(fp->u.a.f_mask))
4088 		return (B_FALSE);
4089 	IN6_V4MAPPED_TO_IPADDR(&fp->u.a.f_mask, fmask);
4090 	if (fmask != IP_HOST_MASK) {
4091 		if (fmask > mask)
4092 			return (B_FALSE);
4093 		mask = fmask;
4094 	}
4095 	for (app = fp->u.a.f_address->h_addr_list; (aptr = *app) != NULL; app++)
4096 		/* LINTED: (note 1) */
4097 		if (IN6_IS_ADDR_V4MAPPED((in6_addr_t *)aptr)) {
4098 			/* LINTED: (note 1) */
4099 			IN6_V4MAPPED_TO_IPADDR((in6_addr_t *)aptr, faddr);
4100 			if (((faddr ^ addr) & mask) == 0)
4101 				return (B_TRUE);
4102 		}
4103 	return (B_FALSE);
4104 }
4105 
4106 /*
4107  * Run through the filter list for an IPv4 MIB2 route entry.  If all
4108  * filters of a given type fail to match, then the route is filtered
4109  * out (not displayed).  If no filter is given or at least one filter
4110  * of each type matches, then display the route.
4111  */
4112 static boolean_t
4113 ire_filter_match_v4(const mib2_ipRouteEntry_t *rp, uint_t flag_b)
4114 {
4115 	filter_t *fp;
4116 	int idx;
4117 
4118 	/* 'for' loop 1: */
4119 	for (idx = 0; idx < NFILTERKEYS; idx++)
4120 		if ((fp = filters[idx]) != NULL) {
4121 			/* 'for' loop 2: */
4122 			for (; fp != NULL; fp = fp->f_next) {
4123 				switch (idx) {
4124 				case FK_AF:
4125 					if (fp->u.f_family != AF_INET)
4126 						continue; /* 'for' loop 2 */
4127 					break;
4128 				case FK_OUTIF:
4129 					if (!dev_name_match(&rp->ipRouteIfIndex,
4130 					    fp->u.f_ifname))
4131 						continue; /* 'for' loop 2 */
4132 					break;
4133 				case FK_DST:
4134 					if (!v4_addr_match(rp->ipRouteDest,
4135 					    rp->ipRouteMask, fp))
4136 						continue; /* 'for' loop 2 */
4137 					break;
4138 				case FK_FLAGS:
4139 					if ((flag_b & fp->u.f.f_flagset) !=
4140 					    fp->u.f.f_flagset ||
4141 					    (flag_b & fp->u.f.f_flagclear))
4142 						continue; /* 'for' loop 2 */
4143 					break;
4144 				}
4145 				break;
4146 			} /* 'for' loop 2 ends */
4147 			if (fp == NULL)
4148 				return (B_FALSE);
4149 		}
4150 	/* 'for' loop 1 ends */
4151 	return (B_TRUE);
4152 }
4153 
4154 /*
4155  * Given an IPv4 MIB2 route entry, form the list of flags for the
4156  * route.
4157  */
4158 static uint_t
4159 form_v4_route_flags(const mib2_ipRouteEntry_t *rp, char *flags)
4160 {
4161 	uint_t flag_b;
4162 
4163 	flag_b = FLF_U;
4164 	(void) strcpy(flags, "U");
4165 	if (rp->ipRouteInfo.re_ire_type == IRE_DEFAULT ||
4166 	    rp->ipRouteInfo.re_ire_type == IRE_PREFIX ||
4167 	    rp->ipRouteInfo.re_ire_type == IRE_HOST ||
4168 	    rp->ipRouteInfo.re_ire_type == IRE_HOST_REDIRECT) {
4169 		(void) strcat(flags, "G");
4170 		flag_b |= FLF_G;
4171 	}
4172 	if (rp->ipRouteMask == IP_HOST_MASK) {
4173 		(void) strcat(flags, "H");
4174 		flag_b |= FLF_H;
4175 	}
4176 	if (rp->ipRouteInfo.re_ire_type == IRE_HOST_REDIRECT) {
4177 		(void) strcat(flags, "D");
4178 		flag_b |= FLF_D;
4179 	}
4180 	if (rp->ipRouteInfo.re_ire_type == IRE_CACHE) {
4181 		/* Address resolution */
4182 		(void) strcat(flags, "A");
4183 		flag_b |= FLF_A;
4184 	}
4185 	if (rp->ipRouteInfo.re_ire_type == IRE_BROADCAST) {	/* Broadcast */
4186 		(void) strcat(flags, "B");
4187 		flag_b |= FLF_B;
4188 	}
4189 	if (rp->ipRouteInfo.re_ire_type == IRE_LOCAL) {		/* Local */
4190 		(void) strcat(flags, "L");
4191 		flag_b |= FLF_L;
4192 	}
4193 	if (rp->ipRouteInfo.re_flags & RTF_MULTIRT) {
4194 		(void) strcat(flags, "M");			/* Multiroute */
4195 		flag_b |= FLF_M;
4196 	}
4197 	if (rp->ipRouteInfo.re_flags & RTF_SETSRC) {
4198 		(void) strcat(flags, "S");			/* Setsrc */
4199 		flag_b |= FLF_S;
4200 	}
4201 	return (flag_b);
4202 }
4203 
4204 static const char ire_hdr_v4[] =
4205 "\n%s Table: IPv4\n";
4206 static const char ire_hdr_v4_compat[] =
4207 "\n%s Table:\n";
4208 static const char ire_hdr_v4_verbose[] =
4209 "  Destination             Mask           Gateway          Device Mxfrg "
4210 "Rtt   Ref Flg  Out  In/Fwd %s\n"
4211 "-------------------- --------------- -------------------- ------ ----- "
4212 "----- --- --- ----- ------ %s\n";
4213 
4214 static const char ire_hdr_v4_normal[] =
4215 "  Destination           Gateway           Flags  Ref     Use     Interface"
4216 " %s\n-------------------- -------------------- ----- ----- ---------- "
4217 "--------- %s\n";
4218 
4219 static boolean_t
4220 ire_report_item_v4(const mib2_ipRouteEntry_t *rp, boolean_t first,
4221     const sec_attr_list_t *attrs)
4222 {
4223 	char			dstbuf[MAXHOSTNAMELEN + 1];
4224 	char			maskbuf[MAXHOSTNAMELEN + 1];
4225 	char			gwbuf[MAXHOSTNAMELEN + 1];
4226 	char			ifname[LIFNAMSIZ + 1];
4227 	char			flags[10];	/* RTF_ flags */
4228 	uint_t			flag_b;
4229 
4230 	if (!(Aflag || (rp->ipRouteInfo.re_ire_type != IRE_CACHE &&
4231 	    rp->ipRouteInfo.re_ire_type != IRE_BROADCAST &&
4232 	    rp->ipRouteInfo.re_ire_type != IRE_LOCAL))) {
4233 		return (first);
4234 	}
4235 
4236 	flag_b = form_v4_route_flags(rp, flags);
4237 
4238 	if (!ire_filter_match_v4(rp, flag_b))
4239 		return (first);
4240 
4241 	if (first) {
4242 		(void) printf(v4compat ? ire_hdr_v4_compat : ire_hdr_v4,
4243 		    Vflag ? "IRE" : "Routing");
4244 		(void) printf(Vflag ? ire_hdr_v4_verbose : ire_hdr_v4_normal,
4245 		    RSECflag ? "  Gateway security attributes  " : "",
4246 		    RSECflag ? "-------------------------------" : "");
4247 		first = B_FALSE;
4248 	}
4249 
4250 	if (flag_b & FLF_H) {
4251 		(void) pr_addr(rp->ipRouteDest, dstbuf, sizeof (dstbuf));
4252 	} else {
4253 		(void) pr_net(rp->ipRouteDest, rp->ipRouteMask,
4254 		    dstbuf, sizeof (dstbuf));
4255 	}
4256 	if (Vflag) {
4257 		(void) printf("%-20s %-15s %-20s %-6s %5u%c %4u %3u "
4258 		    "%-4s%6u %6u %s\n",
4259 		    dstbuf,
4260 		    pr_mask(rp->ipRouteMask, maskbuf, sizeof (maskbuf)),
4261 		    pr_addrnz(rp->ipRouteNextHop, gwbuf, sizeof (gwbuf)),
4262 		    octetstr(&rp->ipRouteIfIndex, 'a', ifname, sizeof (ifname)),
4263 		    rp->ipRouteInfo.re_max_frag,
4264 		    rp->ipRouteInfo.re_frag_flag ? '*' : ' ',
4265 		    rp->ipRouteInfo.re_rtt,
4266 		    rp->ipRouteInfo.re_ref,
4267 		    flags,
4268 		    rp->ipRouteInfo.re_obpkt,
4269 		    rp->ipRouteInfo.re_ibpkt,
4270 		    pr_secattr(attrs));
4271 	} else {
4272 		(void) printf("%-20s %-20s %-5s  %4u %10u %-9s %s\n",
4273 		    dstbuf,
4274 		    pr_addrnz(rp->ipRouteNextHop, gwbuf, sizeof (gwbuf)),
4275 		    flags,
4276 		    rp->ipRouteInfo.re_ref,
4277 		    rp->ipRouteInfo.re_obpkt + rp->ipRouteInfo.re_ibpkt,
4278 		    octetstr(&rp->ipRouteIfIndex, 'a',
4279 		    ifname, sizeof (ifname)),
4280 		    pr_secattr(attrs));
4281 	}
4282 	return (first);
4283 }
4284 
4285 /*
4286  * Match a user-supplied IP address list against an IPv6 route entry.
4287  * If the user specified "any," then any non-zero address matches.  If
4288  * the user specified "none," then only the zero address matches.  If
4289  * the user specified a subnet mask length, then use that in matching
4290  * routes (select routes that are at least as specific).  If the user
4291  * specified only an address, then use the route's mask (select routes
4292  * that would match that address).  IPv4 addresses are ignored.
4293  */
4294 static boolean_t
4295 v6_addr_match(const Ip6Address *addr, int masklen, const filter_t *fp)
4296 {
4297 	const uint8_t *ucp;
4298 	int fmasklen;
4299 	int i;
4300 	char **app;
4301 	char *aptr;
4302 
4303 	if (fp->u.a.f_address == NULL) {
4304 		if (IN6_IS_ADDR_UNSPECIFIED(&fp->u.a.f_mask))	/* any */
4305 			return (!IN6_IS_ADDR_UNSPECIFIED(addr));
4306 		return (IN6_IS_ADDR_UNSPECIFIED(addr));		/* "none" */
4307 	}
4308 	fmasklen = 0;
4309 	/* 'for' loop 1a: */
4310 	for (ucp = fp->u.a.f_mask.s6_addr;
4311 	    ucp < fp->u.a.f_mask.s6_addr + sizeof (fp->u.a.f_mask.s6_addr);
4312 	    ucp++) {
4313 		if (*ucp != 0xff) {
4314 			if (*ucp != 0)
4315 				fmasklen += 9 - ffs(*ucp);
4316 			break; /* 'for' loop 1a */
4317 		}
4318 		fmasklen += 8;
4319 	} /* 'for' loop 1a ends */
4320 	if (fmasklen != IPV6_ABITS) {
4321 		if (fmasklen > masklen)
4322 			return (B_FALSE);
4323 		masklen = fmasklen;
4324 	}
4325 	/* 'for' loop 1b: */
4326 	for (app = fp->u.a.f_address->h_addr_list; (aptr = *app) != NULL;
4327 	    app++) {
4328 		/* LINTED: (note 1) */
4329 		if (IN6_IS_ADDR_V4MAPPED((in6_addr_t *)aptr))
4330 			continue; /* 'for' loop 1b */
4331 		ucp = addr->s6_addr;
4332 		for (i = masklen; i >= 8; i -= 8)
4333 			if (*ucp++ != *aptr++)
4334 				break; /* 'for' loop 1b */
4335 		if (i == 0 ||
4336 		    (i < 8 && ((*ucp ^ *aptr) & ~(0xff >> i)) == 0))
4337 			return (B_TRUE);
4338 	} /* 'for' loop 1b ends */
4339 	return (B_FALSE);
4340 }
4341 
4342 /*
4343  * Run through the filter list for an IPv6 MIB2 IRE.  For a given
4344  * type, if there's at least one filter and all filters of that type
4345  * fail to match, then the route doesn't match and isn't displayed.
4346  * If at least one matches, or none are specified, for each of the
4347  * types, then the route is selected and displayed.
4348  */
4349 static boolean_t
4350 ire_filter_match_v6(const mib2_ipv6RouteEntry_t *rp6, uint_t flag_b)
4351 {
4352 	filter_t *fp;
4353 	int idx;
4354 
4355 	/* 'for' loop 1: */
4356 	for (idx = 0; idx < NFILTERKEYS; idx++)
4357 		if ((fp = filters[idx]) != NULL) {
4358 			/* 'for' loop 2: */
4359 			for (; fp != NULL; fp = fp->f_next) {
4360 				switch (idx) {
4361 				case FK_AF:
4362 					if (fp->u.f_family != AF_INET6)
4363 						/* 'for' loop 2 */
4364 						continue;
4365 					break;
4366 				case FK_OUTIF:
4367 					if (!dev_name_match(&rp6->
4368 					    ipv6RouteIfIndex, fp->u.f_ifname))
4369 						/* 'for' loop 2 */
4370 						continue;
4371 					break;
4372 				case FK_DST:
4373 					if (!v6_addr_match(&rp6->ipv6RouteDest,
4374 					    rp6->ipv6RoutePfxLength, fp))
4375 						/* 'for' loop 2 */
4376 						continue;
4377 					break;
4378 				case FK_FLAGS:
4379 					if ((flag_b & fp->u.f.f_flagset) !=
4380 					    fp->u.f.f_flagset ||
4381 					    (flag_b & fp->u.f.f_flagclear))
4382 						/* 'for' loop 2 */
4383 						continue;
4384 					break;
4385 				}
4386 				break;
4387 			} /* 'for' loop 2 ends */
4388 			if (fp == NULL)
4389 				return (B_FALSE);
4390 		}
4391 	/* 'for' loop 1 ends */
4392 	return (B_TRUE);
4393 }
4394 
4395 static const char ire_hdr_v6[] =
4396 "\n%s Table: IPv6\n";
4397 static const char ire_hdr_v6_verbose[] =
4398 "  Destination/Mask            Gateway                    If    PMTU   Rtt  "
4399 "Ref Flags  Out   In/Fwd %s\n"
4400 "--------------------------- --------------------------- ----- ------ ----- "
4401 "--- ----- ------ ------ %s\n";
4402 static const char ire_hdr_v6_normal[] =
4403 "  Destination/Mask            Gateway                   Flags Ref   Use  "
4404 "  If   %s\n"
4405 "--------------------------- --------------------------- ----- --- ------- "
4406 "----- %s\n";
4407 
4408 static boolean_t
4409 ire_report_item_v6(const mib2_ipv6RouteEntry_t *rp6, boolean_t first,
4410     const sec_attr_list_t *attrs)
4411 {
4412 	char			dstbuf[MAXHOSTNAMELEN + 1];
4413 	char			gwbuf[MAXHOSTNAMELEN + 1];
4414 	char			ifname[LIFNAMSIZ + 1];
4415 	char			flags[10];	/* RTF_ flags */
4416 	uint_t			flag_b;
4417 
4418 	if (!(Aflag || (rp6->ipv6RouteInfo.re_ire_type != IRE_CACHE &&
4419 	    rp6->ipv6RouteInfo.re_ire_type != IRE_LOCAL))) {
4420 		return (first);
4421 	}
4422 
4423 	flag_b = FLF_U;
4424 	(void) strcpy(flags, "U");
4425 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_DEFAULT ||
4426 	    rp6->ipv6RouteInfo.re_ire_type == IRE_PREFIX ||
4427 	    rp6->ipv6RouteInfo.re_ire_type == IRE_HOST ||
4428 	    rp6->ipv6RouteInfo.re_ire_type == IRE_HOST_REDIRECT) {
4429 		(void) strcat(flags, "G");
4430 		flag_b |= FLF_G;
4431 	}
4432 
4433 	if (rp6->ipv6RoutePfxLength == IPV6_ABITS) {
4434 		(void) strcat(flags, "H");
4435 		flag_b |= FLF_H;
4436 	}
4437 
4438 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_HOST_REDIRECT) {
4439 		(void) strcat(flags, "D");
4440 		flag_b |= FLF_D;
4441 	}
4442 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_CACHE) {
4443 		/* Address resolution */
4444 		(void) strcat(flags, "A");
4445 		flag_b |= FLF_A;
4446 	}
4447 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_LOCAL) {	/* Local */
4448 		(void) strcat(flags, "L");
4449 		flag_b |= FLF_L;
4450 	}
4451 	if (rp6->ipv6RouteInfo.re_flags & RTF_MULTIRT) {
4452 		(void) strcat(flags, "M");			/* Multiroute */
4453 		flag_b |= FLF_M;
4454 	}
4455 	if (rp6->ipv6RouteInfo.re_flags & RTF_SETSRC) {
4456 		(void) strcat(flags, "S");			/* Setsrc */
4457 		flag_b |= FLF_S;
4458 	}
4459 
4460 	if (!ire_filter_match_v6(rp6, flag_b))
4461 		return (first);
4462 
4463 	if (first) {
4464 		(void) printf(ire_hdr_v6, Vflag ? "IRE" : "Routing");
4465 		(void) printf(Vflag ? ire_hdr_v6_verbose : ire_hdr_v6_normal,
4466 		    RSECflag ? "  Gateway security attributes  " : "",
4467 		    RSECflag ? "-------------------------------" : "");
4468 		first = B_FALSE;
4469 	}
4470 
4471 	if (Vflag) {
4472 		(void) printf("%-27s %-27s %-5s %5u%c %5u %3u "
4473 		    "%-5s %6u %6u %s\n",
4474 		    pr_prefix6(&rp6->ipv6RouteDest,
4475 			rp6->ipv6RoutePfxLength, dstbuf, sizeof (dstbuf)),
4476 		    IN6_IS_ADDR_UNSPECIFIED(&rp6->ipv6RouteNextHop) ?
4477 		    "    --" :
4478 		    pr_addr6(&rp6->ipv6RouteNextHop, gwbuf, sizeof (gwbuf)),
4479 		    octetstr(&rp6->ipv6RouteIfIndex, 'a',
4480 		    ifname, sizeof (ifname)),
4481 		    rp6->ipv6RouteInfo.re_max_frag,
4482 		    rp6->ipv6RouteInfo.re_frag_flag ? '*' : ' ',
4483 		    rp6->ipv6RouteInfo.re_rtt,
4484 		    rp6->ipv6RouteInfo.re_ref,
4485 		    flags,
4486 		    rp6->ipv6RouteInfo.re_obpkt,
4487 		    rp6->ipv6RouteInfo.re_ibpkt,
4488 		    pr_secattr(attrs));
4489 	} else {
4490 		(void) printf("%-27s %-27s %-5s %3u %7u %-5s %s\n",
4491 		    pr_prefix6(&rp6->ipv6RouteDest,
4492 			rp6->ipv6RoutePfxLength, dstbuf, sizeof (dstbuf)),
4493 		    IN6_IS_ADDR_UNSPECIFIED(&rp6->ipv6RouteNextHop) ?
4494 		    "    --" :
4495 		    pr_addr6(&rp6->ipv6RouteNextHop, gwbuf, sizeof (gwbuf)),
4496 		    flags,
4497 		    rp6->ipv6RouteInfo.re_ref,
4498 		    rp6->ipv6RouteInfo.re_obpkt + rp6->ipv6RouteInfo.re_ibpkt,
4499 		    octetstr(&rp6->ipv6RouteIfIndex, 'a',
4500 		    ifname, sizeof (ifname)),
4501 		    pr_secattr(attrs));
4502 	}
4503 	return (first);
4504 }
4505 
4506 /*
4507  * Common attribute-gathering routine for all transports.
4508  */
4509 static mib2_transportMLPEntry_t **
4510 gather_attrs(const mib_item_t *item, int group, int mib_id, int esize)
4511 {
4512 	int transport_count = 0;
4513 	const mib_item_t *iptr;
4514 	mib2_transportMLPEntry_t **attrs, *tme;
4515 
4516 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
4517 		if (iptr->group == group && iptr->mib_id == mib_id)
4518 			transport_count += iptr->length / esize;
4519 	}
4520 	if (transport_count <= 0)
4521 		return (NULL);
4522 	attrs = calloc(transport_count, sizeof (*attrs));
4523 	if (attrs == NULL) {
4524 		perror("gather_attrs calloc failed");
4525 		return (NULL);
4526 	}
4527 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
4528 		if (iptr->group == group && iptr->mib_id == EXPER_XPORT_MLP) {
4529 			for (tme = iptr->valp;
4530 			    (char *)tme < (char *)iptr->valp + iptr->length;
4531 			    /* LINTED: (note 1) */
4532 			    tme = (mib2_transportMLPEntry_t *)((char *)tme +
4533 			    transportMLPSize)) {
4534 				attrs[tme->tme_connidx] = tme;
4535 			}
4536 		}
4537 	}
4538 	return (attrs);
4539 }
4540 
4541 static void
4542 print_transport_label(const mib2_transportMLPEntry_t *attr)
4543 {
4544 	if (!RSECflag || attr == NULL)
4545 		return;
4546 
4547 	if (bisinvalid(&attr->tme_label))
4548 		(void) printf("   INVALID\n");
4549 	else
4550 		(void) printf("   %s\n", sl_to_str(&attr->tme_label));
4551 }
4552 
4553 /* ------------------------------ TCP_REPORT------------------------------- */
4554 
4555 static const char tcp_hdr_v4[] =
4556 "\nTCP: IPv4\n";
4557 static const char tcp_hdr_v4_compat[] =
4558 "\nTCP\n";
4559 static const char tcp_hdr_v4_verbose[] =
4560 "Local/Remote Address Swind  Snext     Suna   Rwind  Rnext     Rack   "
4561 " Rto   Mss     State\n"
4562 "-------------------- ----- -------- -------- ----- -------- -------- "
4563 "----- ----- -----------\n";
4564 static const char tcp_hdr_v4_normal[] =
4565 "   Local Address        Remote Address    Swind Send-Q Rwind Recv-Q "
4566 "   State\n"
4567 "-------------------- -------------------- ----- ------ ----- ------ "
4568 "-----------\n";
4569 
4570 static const char tcp_hdr_v6[] =
4571 "\nTCP: IPv6\n";
4572 static const char tcp_hdr_v6_verbose[] =
4573 "Local/Remote Address              Swind  Snext     Suna   Rwind  Rnext   "
4574 "  Rack    Rto   Mss    State      If\n"
4575 "--------------------------------- ----- -------- -------- ----- -------- "
4576 "-------- ----- ----- ----------- -----\n";
4577 static const char tcp_hdr_v6_normal[] =
4578 "   Local Address                     Remote Address                 "
4579 "Swind Send-Q Rwind Recv-Q   State      If\n"
4580 "--------------------------------- --------------------------------- "
4581 "----- ------ ----- ------ ----------- -----\n";
4582 
4583 static boolean_t tcp_report_item_v4(const mib2_tcpConnEntry_t *,
4584     boolean_t first, const mib2_transportMLPEntry_t *);
4585 static boolean_t tcp_report_item_v6(const mib2_tcp6ConnEntry_t *,
4586     boolean_t first, const mib2_transportMLPEntry_t *);
4587 
4588 static void
4589 tcp_report(const mib_item_t *item)
4590 {
4591 	int			jtemp = 0;
4592 	boolean_t		print_hdr_once_v4 = B_TRUE;
4593 	boolean_t		print_hdr_once_v6 = B_TRUE;
4594 	mib2_tcpConnEntry_t	*tp;
4595 	mib2_tcp6ConnEntry_t	*tp6;
4596 	mib2_transportMLPEntry_t **v4_attrs, **v6_attrs;
4597 	mib2_transportMLPEntry_t **v4a, **v6a;
4598 	mib2_transportMLPEntry_t *aptr;
4599 
4600 	if (!protocol_selected(IPPROTO_TCP))
4601 		return;
4602 
4603 	/*
4604 	 * Preparation pass: the kernel returns separate entries for TCP
4605 	 * connection table entries and Multilevel Port attributes.  We loop
4606 	 * through the attributes first and set up an array for each address
4607 	 * family.
4608 	 */
4609 	v4_attrs = family_selected(AF_INET) && RSECflag ?
4610 	    gather_attrs(item, MIB2_TCP, MIB2_TCP_CONN, tcpConnEntrySize) :
4611 	    NULL;
4612 	v6_attrs = family_selected(AF_INET6) && RSECflag ?
4613 	    gather_attrs(item, MIB2_TCP6, MIB2_TCP6_CONN, tcp6ConnEntrySize) :
4614 	    NULL;
4615 
4616 	/* 'for' loop 1: */
4617 	v4a = v4_attrs;
4618 	v6a = v6_attrs;
4619 	for (; item != NULL; item = item->next_item) {
4620 		if (Dflag) {
4621 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
4622 			(void) printf("Group = %d, mib_id = %d, "
4623 			    "length = %d, valp = 0x%p\n",
4624 			    item->group, item->mib_id,
4625 			    item->length, item->valp);
4626 		}
4627 
4628 		if (!((item->group == MIB2_TCP &&
4629 		    item->mib_id == MIB2_TCP_CONN) ||
4630 		    (item->group == MIB2_TCP6 &&
4631 		    item->mib_id == MIB2_TCP6_CONN)))
4632 			continue; /* 'for' loop 1 */
4633 
4634 		if (item->group == MIB2_TCP && !family_selected(AF_INET))
4635 			continue; /* 'for' loop 1 */
4636 		else if (item->group == MIB2_TCP6 && !family_selected(AF_INET6))
4637 			continue; /* 'for' loop 1 */
4638 
4639 		if (item->group == MIB2_TCP) {
4640 			for (tp = (mib2_tcpConnEntry_t *)item->valp;
4641 			    (char *)tp < (char *)item->valp + item->length;
4642 			    /* LINTED: (note 1) */
4643 			    tp = (mib2_tcpConnEntry_t *)((char *)tp +
4644 			    tcpConnEntrySize)) {
4645 				aptr = v4a == NULL ? NULL : *v4a++;
4646 				print_hdr_once_v4 = tcp_report_item_v4(tp,
4647 				    print_hdr_once_v4, aptr);
4648 			}
4649 		} else {
4650 			for (tp6 = (mib2_tcp6ConnEntry_t *)item->valp;
4651 			    (char *)tp6 < (char *)item->valp + item->length;
4652 			    /* LINTED: (note 1) */
4653 			    tp6 = (mib2_tcp6ConnEntry_t *)((char *)tp6 +
4654 			    tcp6ConnEntrySize)) {
4655 				aptr = v6a == NULL ? NULL : *v6a++;
4656 				print_hdr_once_v6 = tcp_report_item_v6(tp6,
4657 				    print_hdr_once_v6, aptr);
4658 			}
4659 		}
4660 	} /* 'for' loop 1 ends */
4661 	(void) fflush(stdout);
4662 
4663 	if (v4_attrs != NULL)
4664 		free(v4_attrs);
4665 	if (v6_attrs != NULL)
4666 		free(v6_attrs);
4667 }
4668 
4669 static boolean_t
4670 tcp_report_item_v4(const mib2_tcpConnEntry_t *tp, boolean_t first,
4671     const mib2_transportMLPEntry_t *attr)
4672 {
4673 	/*
4674 	 * lname and fname below are for the hostname as well as the portname
4675 	 * There is no limit on portname length so we assume MAXHOSTNAMELEN
4676 	 * as the limit
4677 	 */
4678 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4679 	char	fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4680 
4681 	if (!(Aflag || tp->tcpConnEntryInfo.ce_state >= TCPS_ESTABLISHED))
4682 		return (first); /* Nothing to print */
4683 
4684 	if (first) {
4685 		(void) printf(v4compat ? tcp_hdr_v4_compat : tcp_hdr_v4);
4686 		(void) printf(Vflag ? tcp_hdr_v4_verbose : tcp_hdr_v4_normal);
4687 	}
4688 
4689 	if (Vflag) {
4690 		(void) printf("%-20s\n%-20s %5u %08x %08x %5u %08x %08x "
4691 		    "%5u %5u %s\n",
4692 		    pr_ap(tp->tcpConnLocalAddress,
4693 			tp->tcpConnLocalPort, "tcp", lname, sizeof (lname)),
4694 		    pr_ap(tp->tcpConnRemAddress,
4695 			tp->tcpConnRemPort, "tcp", fname, sizeof (fname)),
4696 		    tp->tcpConnEntryInfo.ce_swnd,
4697 		    tp->tcpConnEntryInfo.ce_snxt,
4698 		    tp->tcpConnEntryInfo.ce_suna,
4699 		    tp->tcpConnEntryInfo.ce_rwnd,
4700 		    tp->tcpConnEntryInfo.ce_rnxt,
4701 		    tp->tcpConnEntryInfo.ce_rack,
4702 		    tp->tcpConnEntryInfo.ce_rto,
4703 		    tp->tcpConnEntryInfo.ce_mss,
4704 		    mitcp_state(tp->tcpConnEntryInfo.ce_state, attr));
4705 	} else {
4706 		int sq = (int)tp->tcpConnEntryInfo.ce_snxt -
4707 		    (int)tp->tcpConnEntryInfo.ce_suna - 1;
4708 		int rq = (int)tp->tcpConnEntryInfo.ce_rnxt -
4709 		    (int)tp->tcpConnEntryInfo.ce_rack;
4710 
4711 		(void) printf("%-20s %-20s %5u %6d %5u %6d %s\n",
4712 		    pr_ap(tp->tcpConnLocalAddress,
4713 			tp->tcpConnLocalPort, "tcp", lname, sizeof (lname)),
4714 		    pr_ap(tp->tcpConnRemAddress,
4715 			tp->tcpConnRemPort, "tcp", fname, sizeof (fname)),
4716 		    tp->tcpConnEntryInfo.ce_swnd,
4717 		    (sq >= 0) ? sq : 0,
4718 		    tp->tcpConnEntryInfo.ce_rwnd,
4719 		    (rq >= 0) ? rq : 0,
4720 		    mitcp_state(tp->tcpConnEntryInfo.ce_state, attr));
4721 	}
4722 
4723 	print_transport_label(attr);
4724 
4725 	return (B_FALSE);
4726 }
4727 
4728 static boolean_t
4729 tcp_report_item_v6(const mib2_tcp6ConnEntry_t *tp6, boolean_t first,
4730     const mib2_transportMLPEntry_t *attr)
4731 {
4732 	/*
4733 	 * lname and fname below are for the hostname as well as the portname
4734 	 * There is no limit on portname length so we assume MAXHOSTNAMELEN
4735 	 * as the limit
4736 	 */
4737 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4738 	char	fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4739 	char	ifname[LIFNAMSIZ + 1];
4740 	char	*ifnamep;
4741 
4742 	if (!(Aflag || tp6->tcp6ConnEntryInfo.ce_state >= TCPS_ESTABLISHED))
4743 		return (first); /* Nothing to print */
4744 
4745 	if (first) {
4746 		(void) printf(tcp_hdr_v6);
4747 		(void) printf(Vflag ? tcp_hdr_v6_verbose : tcp_hdr_v6_normal);
4748 	}
4749 
4750 	ifnamep = (tp6->tcp6ConnIfIndex != 0) ?
4751 	    if_indextoname(tp6->tcp6ConnIfIndex, ifname) : NULL;
4752 	if (ifnamep == NULL)
4753 		ifnamep = "";
4754 
4755 	if (Vflag) {
4756 		(void) printf("%-33s\n%-33s %5u %08x %08x %5u %08x %08x "
4757 		    "%5u %5u %-11s %s\n",
4758 		    pr_ap6(&tp6->tcp6ConnLocalAddress,
4759 			tp6->tcp6ConnLocalPort, "tcp", lname, sizeof (lname)),
4760 		    pr_ap6(&tp6->tcp6ConnRemAddress,
4761 			tp6->tcp6ConnRemPort, "tcp", fname, sizeof (fname)),
4762 		    tp6->tcp6ConnEntryInfo.ce_swnd,
4763 		    tp6->tcp6ConnEntryInfo.ce_snxt,
4764 		    tp6->tcp6ConnEntryInfo.ce_suna,
4765 		    tp6->tcp6ConnEntryInfo.ce_rwnd,
4766 		    tp6->tcp6ConnEntryInfo.ce_rnxt,
4767 		    tp6->tcp6ConnEntryInfo.ce_rack,
4768 		    tp6->tcp6ConnEntryInfo.ce_rto,
4769 		    tp6->tcp6ConnEntryInfo.ce_mss,
4770 		    mitcp_state(tp6->tcp6ConnEntryInfo.ce_state, attr),
4771 		    ifnamep);
4772 	} else {
4773 		int sq = (int)tp6->tcp6ConnEntryInfo.ce_snxt -
4774 		    (int)tp6->tcp6ConnEntryInfo.ce_suna - 1;
4775 		int rq = (int)tp6->tcp6ConnEntryInfo.ce_rnxt -
4776 		    (int)tp6->tcp6ConnEntryInfo.ce_rack;
4777 
4778 		(void) printf("%-33s %-33s %5u %6d %5u %6d %-11s %s\n",
4779 		    pr_ap6(&tp6->tcp6ConnLocalAddress,
4780 			tp6->tcp6ConnLocalPort, "tcp", lname, sizeof (lname)),
4781 		    pr_ap6(&tp6->tcp6ConnRemAddress,
4782 			tp6->tcp6ConnRemPort, "tcp", fname, sizeof (fname)),
4783 		    tp6->tcp6ConnEntryInfo.ce_swnd,
4784 		    (sq >= 0) ? sq : 0,
4785 		    tp6->tcp6ConnEntryInfo.ce_rwnd,
4786 		    (rq >= 0) ? rq : 0,
4787 		    mitcp_state(tp6->tcp6ConnEntryInfo.ce_state, attr),
4788 		    ifnamep);
4789 	}
4790 
4791 	print_transport_label(attr);
4792 
4793 	return (B_FALSE);
4794 }
4795 
4796 /* ------------------------------- UDP_REPORT------------------------------- */
4797 
4798 static boolean_t udp_report_item_v4(const mib2_udpEntry_t *ude,
4799     boolean_t first, const mib2_transportMLPEntry_t *attr);
4800 static boolean_t udp_report_item_v6(const mib2_udp6Entry_t *ude6,
4801     boolean_t first, const mib2_transportMLPEntry_t *attr);
4802 
4803 static const char udp_hdr_v4[] =
4804 "   Local Address        Remote Address      State\n"
4805 "-------------------- -------------------- ----------\n";
4806 
4807 static const char udp_hdr_v6[] =
4808 "   Local Address                     Remote Address                 "
4809 "  State      If\n"
4810 "--------------------------------- --------------------------------- "
4811 "---------- -----\n";
4812 
4813 static void
4814 udp_report(const mib_item_t *item)
4815 {
4816 	int			jtemp = 0;
4817 	boolean_t		print_hdr_once_v4 = B_TRUE;
4818 	boolean_t		print_hdr_once_v6 = B_TRUE;
4819 	mib2_udpEntry_t		*ude;
4820 	mib2_udp6Entry_t	*ude6;
4821 	mib2_transportMLPEntry_t **v4_attrs, **v6_attrs;
4822 	mib2_transportMLPEntry_t **v4a, **v6a;
4823 	mib2_transportMLPEntry_t *aptr;
4824 
4825 	if (!protocol_selected(IPPROTO_UDP))
4826 		return;
4827 
4828 	/*
4829 	 * Preparation pass: the kernel returns separate entries for UDP
4830 	 * connection table entries and Multilevel Port attributes.  We loop
4831 	 * through the attributes first and set up an array for each address
4832 	 * family.
4833 	 */
4834 	v4_attrs = family_selected(AF_INET) && RSECflag ?
4835 	    gather_attrs(item, MIB2_UDP, MIB2_UDP_ENTRY, udpEntrySize) : NULL;
4836 	v6_attrs = family_selected(AF_INET6) && RSECflag ?
4837 	    gather_attrs(item, MIB2_UDP6, MIB2_UDP6_ENTRY, udp6EntrySize) :
4838 	    NULL;
4839 
4840 	v4a = v4_attrs;
4841 	v6a = v6_attrs;
4842 	/* 'for' loop 1: */
4843 	for (; item; item = item->next_item) {
4844 		if (Dflag) {
4845 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
4846 			(void) printf("Group = %d, mib_id = %d, "
4847 			    "length = %d, valp = 0x%p\n",
4848 			    item->group, item->mib_id,
4849 			    item->length, item->valp);
4850 		}
4851 		if (!((item->group == MIB2_UDP &&
4852 		    item->mib_id == MIB2_UDP_ENTRY) ||
4853 		    (item->group == MIB2_UDP6 &&
4854 		    item->mib_id == MIB2_UDP6_ENTRY)))
4855 			continue; /* 'for' loop 1 */
4856 
4857 		if (item->group == MIB2_UDP && !family_selected(AF_INET))
4858 			continue; /* 'for' loop 1 */
4859 		else if (item->group == MIB2_UDP6 && !family_selected(AF_INET6))
4860 			continue; /* 'for' loop 1 */
4861 
4862 		/*	xxx.xxx.xxx.xxx,pppp  sss... */
4863 		if (item->group == MIB2_UDP) {
4864 			for (ude = (mib2_udpEntry_t *)item->valp;
4865 			    (char *)ude < (char *)item->valp + item->length;
4866 			    /* LINTED: (note 1) */
4867 			    ude = (mib2_udpEntry_t *)((char *)ude +
4868 			    udpEntrySize)) {
4869 				aptr = v4a == NULL ? NULL : *v4a++;
4870 				print_hdr_once_v4 = udp_report_item_v4(ude,
4871 				    print_hdr_once_v4, aptr);
4872 			}
4873 		} else {
4874 			for (ude6 = (mib2_udp6Entry_t *)item->valp;
4875 			    (char *)ude6 < (char *)item->valp + item->length;
4876 			    /* LINTED: (note 1) */
4877 			    ude6 = (mib2_udp6Entry_t *)((char *)ude6 +
4878 			    udp6EntrySize)) {
4879 				aptr = v6a == NULL ? NULL : *v6a++;
4880 				print_hdr_once_v6 = udp_report_item_v6(ude6,
4881 				    print_hdr_once_v6, aptr);
4882 			}
4883 		}
4884 	} /* 'for' loop 1 ends */
4885 	(void) fflush(stdout);
4886 
4887 	if (v4_attrs != NULL)
4888 		free(v4_attrs);
4889 	if (v6_attrs != NULL)
4890 		free(v6_attrs);
4891 }
4892 
4893 static boolean_t
4894 udp_report_item_v4(const mib2_udpEntry_t *ude, boolean_t first,
4895     const mib2_transportMLPEntry_t *attr)
4896 {
4897 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4898 			/* hostname + portname */
4899 
4900 	if (!(Aflag || ude->udpEntryInfo.ue_state >= MIB2_UDP_connected))
4901 		return (first); /* Nothing to print */
4902 
4903 	if (first) {
4904 		(void) printf(v4compat ? "\nUDP\n" : "\nUDP: IPv4\n");
4905 		(void) printf(udp_hdr_v4);
4906 		first = B_FALSE;
4907 	}
4908 
4909 	(void) printf("%-20s ",
4910 	    pr_ap(ude->udpLocalAddress, ude->udpLocalPort, "udp",
4911 	    lname, sizeof (lname)));
4912 	(void) printf("%-20s %s\n",
4913 	    ude->udpEntryInfo.ue_state == MIB2_UDP_connected ?
4914 	    pr_ap(ude->udpEntryInfo.ue_RemoteAddress,
4915 	    ude->udpEntryInfo.ue_RemotePort, "udp", lname, sizeof (lname)) :
4916 	    "",
4917 	    miudp_state(ude->udpEntryInfo.ue_state, attr));
4918 
4919 	/*
4920 	 * UDP sockets don't have remote attributes, so there's no need to
4921 	 * print them here.
4922 	 */
4923 
4924 	return (first);
4925 }
4926 
4927 static boolean_t
4928 udp_report_item_v6(const mib2_udp6Entry_t *ude6, boolean_t first,
4929     const mib2_transportMLPEntry_t *attr)
4930 {
4931 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
4932 			/* hostname + portname */
4933 	char	ifname[LIFNAMSIZ + 1];
4934 	const char *ifnamep;
4935 
4936 	if (!(Aflag || ude6->udp6EntryInfo.ue_state >= MIB2_UDP_connected))
4937 		return (first); /* Nothing to print */
4938 
4939 	if (first) {
4940 		(void) printf("\nUDP: IPv6\n");
4941 		(void) printf(udp_hdr_v6);
4942 		first = B_FALSE;
4943 	}
4944 
4945 	ifnamep = (ude6->udp6IfIndex != 0) ?
4946 	    if_indextoname(ude6->udp6IfIndex, ifname) : NULL;
4947 
4948 	(void) printf("%-33s ",
4949 	    pr_ap6(&ude6->udp6LocalAddress,
4950 	    ude6->udp6LocalPort, "udp", lname, sizeof (lname)));
4951 	(void) printf("%-33s %-10s %s\n",
4952 	    ude6->udp6EntryInfo.ue_state == MIB2_UDP_connected ?
4953 	    pr_ap6(&ude6->udp6EntryInfo.ue_RemoteAddress,
4954 	    ude6->udp6EntryInfo.ue_RemotePort, "udp", lname, sizeof (lname)) :
4955 	    "",
4956 	    miudp_state(ude6->udp6EntryInfo.ue_state, attr),
4957 	    ifnamep == NULL ? "" : ifnamep);
4958 
4959 	/*
4960 	 * UDP sockets don't have remote attributes, so there's no need to
4961 	 * print them here.
4962 	 */
4963 
4964 	return (first);
4965 }
4966 
4967 /* ------------------------------ SCTP_REPORT------------------------------- */
4968 
4969 static const char sctp_hdr[] =
4970 "\nSCTP:";
4971 static const char sctp_hdr_normal[] =
4972 "        Local Address                   Remote Address          "
4973 "Swind  Send-Q Rwind  Recv-Q StrsI/O  State\n"
4974 "------------------------------- ------------------------------- "
4975 "------ ------ ------ ------ ------- -----------";
4976 
4977 static const char *
4978 nssctp_state(int state, const mib2_transportMLPEntry_t *attr)
4979 {
4980 	static char sctpsbuf[50];
4981 	const char *cp;
4982 
4983 	switch (state) {
4984 	case MIB2_SCTP_closed:
4985 		cp = "CLOSED";
4986 		break;
4987 	case MIB2_SCTP_cookieWait:
4988 		cp = "COOKIE_WAIT";
4989 		break;
4990 	case MIB2_SCTP_cookieEchoed:
4991 		cp = "COOKIE_ECHOED";
4992 		break;
4993 	case MIB2_SCTP_established:
4994 		cp = "ESTABLISHED";
4995 		break;
4996 	case MIB2_SCTP_shutdownPending:
4997 		cp = "SHUTDOWN_PENDING";
4998 		break;
4999 	case MIB2_SCTP_shutdownSent:
5000 		cp = "SHUTDOWN_SENT";
5001 		break;
5002 	case MIB2_SCTP_shutdownReceived:
5003 		cp = "SHUTDOWN_RECEIVED";
5004 		break;
5005 	case MIB2_SCTP_shutdownAckSent:
5006 		cp = "SHUTDOWN_ACK_SENT";
5007 		break;
5008 	case MIB2_SCTP_listen:
5009 		cp = "LISTEN";
5010 		break;
5011 	default:
5012 		(void) snprintf(sctpsbuf, sizeof (sctpsbuf),
5013 		    "UNKNOWN STATE(%d)", state);
5014 		cp = sctpsbuf;
5015 		break;
5016 	}
5017 
5018 	if (RSECflag && attr != NULL && attr->tme_flags != 0) {
5019 		if (cp != sctpsbuf) {
5020 			(void) strlcpy(sctpsbuf, cp, sizeof (sctpsbuf));
5021 			cp = sctpsbuf;
5022 		}
5023 		if (attr->tme_flags & MIB2_TMEF_PRIVATE)
5024 			(void) strlcat(sctpsbuf, " P", sizeof (sctpsbuf));
5025 		if (attr->tme_flags & MIB2_TMEF_SHARED)
5026 			(void) strlcat(sctpsbuf, " S", sizeof (sctpsbuf));
5027 	}
5028 
5029 	return (cp);
5030 }
5031 
5032 static const mib2_sctpConnRemoteEntry_t *
5033 sctp_getnext_rem(const mib_item_t **itemp,
5034     const mib2_sctpConnRemoteEntry_t *current, uint32_t associd)
5035 {
5036 	const mib_item_t *item = *itemp;
5037 	const mib2_sctpConnRemoteEntry_t	*sre;
5038 
5039 	for (; item != NULL; item = item->next_item, current = NULL) {
5040 		if (!(item->group == MIB2_SCTP &&
5041 		    item->mib_id == MIB2_SCTP_CONN_REMOTE)) {
5042 			continue;
5043 		}
5044 
5045 		if (current != NULL) {
5046 			/* LINTED: (note 1) */
5047 			sre = (const mib2_sctpConnRemoteEntry_t *)
5048 			    ((const char *)current + sctpRemoteEntrySize);
5049 		} else {
5050 			sre = item->valp;
5051 		}
5052 		for (; (char *)sre < (char *)item->valp + item->length;
5053 		    /* LINTED: (note 1) */
5054 		    sre = (const mib2_sctpConnRemoteEntry_t *)
5055 		    ((const char *)sre + sctpRemoteEntrySize)) {
5056 			if (sre->sctpAssocId != associd) {
5057 				continue;
5058 			}
5059 			*itemp = item;
5060 			return (sre);
5061 		}
5062 	}
5063 	*itemp = NULL;
5064 	return (NULL);
5065 }
5066 
5067 static const mib2_sctpConnLocalEntry_t *
5068 sctp_getnext_local(const mib_item_t **itemp,
5069     const mib2_sctpConnLocalEntry_t *current, uint32_t associd)
5070 {
5071 	const mib_item_t *item = *itemp;
5072 	const mib2_sctpConnLocalEntry_t	*sle;
5073 
5074 	for (; item != NULL; item = item->next_item, current = NULL) {
5075 		if (!(item->group == MIB2_SCTP &&
5076 		    item->mib_id == MIB2_SCTP_CONN_LOCAL)) {
5077 			continue;
5078 		}
5079 
5080 		if (current != NULL) {
5081 			/* LINTED: (note 1) */
5082 			sle = (const mib2_sctpConnLocalEntry_t *)
5083 			    ((const char *)current + sctpLocalEntrySize);
5084 		} else {
5085 			sle = item->valp;
5086 		}
5087 		for (; (char *)sle < (char *)item->valp + item->length;
5088 		    /* LINTED: (note 1) */
5089 		    sle = (const mib2_sctpConnLocalEntry_t *)
5090 		    ((const char *)sle + sctpLocalEntrySize)) {
5091 			if (sle->sctpAssocId != associd) {
5092 				continue;
5093 			}
5094 			*itemp = item;
5095 			return (sle);
5096 		}
5097 	}
5098 	*itemp = NULL;
5099 	return (NULL);
5100 }
5101 
5102 static void
5103 sctp_pr_addr(int type, char *name, int namelen, const in6_addr_t *addr,
5104     int port)
5105 {
5106 	ipaddr_t	v4addr;
5107 	in6_addr_t	v6addr;
5108 
5109 	/*
5110 	 * Address is either a v4 mapped or v6 addr. If
5111 	 * it's a v4 mapped, convert to v4 before
5112 	 * displaying.
5113 	 */
5114 	switch (type) {
5115 	    case MIB2_SCTP_ADDR_V4:
5116 		/* v4 */
5117 		v6addr = *addr;
5118 
5119 		IN6_V4MAPPED_TO_IPADDR(&v6addr, v4addr);
5120 		if (port > 0) {
5121 			(void) pr_ap(v4addr, port, "sctp", name, namelen);
5122 		} else {
5123 			(void) pr_addr(v4addr, name, namelen);
5124 		}
5125 		break;
5126 
5127 	    case MIB2_SCTP_ADDR_V6:
5128 		/* v6 */
5129 		if (port > 0) {
5130 			(void) pr_ap6(addr, port, "sctp", name, namelen);
5131 		} else {
5132 			(void) pr_addr6(addr, name, namelen);
5133 		}
5134 		break;
5135 
5136 	    default:
5137 		(void) snprintf(name, namelen, "<unknown addr type>");
5138 		break;
5139 	}
5140 }
5141 
5142 static void
5143 sctp_conn_report_item(const mib_item_t *head, const mib2_sctpConnEntry_t *sp,
5144     const mib2_transportMLPEntry_t *attr)
5145 {
5146 	char		lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5147 	char		fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5148 	const mib2_sctpConnRemoteEntry_t	*sre = NULL;
5149 	const mib2_sctpConnLocalEntry_t	*sle = NULL;
5150 	const mib_item_t *local = head;
5151 	const mib_item_t *remote = head;
5152 	uint32_t	id = sp->sctpAssocId;
5153 	boolean_t	printfirst = B_TRUE;
5154 
5155 	sctp_pr_addr(sp->sctpAssocRemPrimAddrType, fname, sizeof (fname),
5156 	    &sp->sctpAssocRemPrimAddr, sp->sctpAssocRemPort);
5157 	sctp_pr_addr(sp->sctpAssocRemPrimAddrType, lname, sizeof (lname),
5158 	    &sp->sctpAssocLocPrimAddr, sp->sctpAssocLocalPort);
5159 
5160 	(void) printf("%-31s %-31s %6u %6d %6u %6d %3d/%-3d %s\n",
5161 	    lname, fname,
5162 	    sp->sctpConnEntryInfo.ce_swnd,
5163 	    sp->sctpConnEntryInfo.ce_sendq,
5164 	    sp->sctpConnEntryInfo.ce_rwnd,
5165 	    sp->sctpConnEntryInfo.ce_recvq,
5166 	    sp->sctpAssocInStreams, sp->sctpAssocOutStreams,
5167 	    nssctp_state(sp->sctpAssocState, attr));
5168 
5169 	print_transport_label(attr);
5170 
5171 	if (!Vflag) {
5172 		return;
5173 	}
5174 
5175 	/* Print remote addresses/local addresses on following lines */
5176 	while ((sre = sctp_getnext_rem(&remote, sre, id)) != NULL) {
5177 		if (!IN6_ARE_ADDR_EQUAL(&sre->sctpAssocRemAddr,
5178 		    &sp->sctpAssocRemPrimAddr)) {
5179 			if (printfirst == B_TRUE) {
5180 				(void) fputs("\t<Remote: ", stdout);
5181 				printfirst = B_FALSE;
5182 			} else {
5183 				(void) fputs(", ", stdout);
5184 			}
5185 			sctp_pr_addr(sre->sctpAssocRemAddrType, fname,
5186 			    sizeof (fname), &sre->sctpAssocRemAddr, -1);
5187 			if (sre->sctpAssocRemAddrActive == MIB2_SCTP_ACTIVE) {
5188 				(void) fputs(fname, stdout);
5189 			} else {
5190 				(void) printf("(%s)", fname);
5191 			}
5192 		}
5193 	}
5194 	if (printfirst == B_FALSE) {
5195 		(void) puts(">");
5196 		printfirst = B_TRUE;
5197 	}
5198 	while ((sle = sctp_getnext_local(&local, sle, id)) != NULL) {
5199 		if (!IN6_ARE_ADDR_EQUAL(&sle->sctpAssocLocalAddr,
5200 		    &sp->sctpAssocLocPrimAddr)) {
5201 			if (printfirst == B_TRUE) {
5202 				(void) fputs("\t<Local: ", stdout);
5203 				printfirst = B_FALSE;
5204 			} else {
5205 				(void) fputs(", ", stdout);
5206 			}
5207 			sctp_pr_addr(sle->sctpAssocLocalAddrType, lname,
5208 			    sizeof (lname), &sle->sctpAssocLocalAddr, -1);
5209 			(void) fputs(lname, stdout);
5210 		}
5211 	}
5212 	if (printfirst == B_FALSE) {
5213 		(void) puts(">");
5214 	}
5215 }
5216 
5217 static void
5218 sctp_report(const mib_item_t *item)
5219 {
5220 	const mib_item_t		*head;
5221 	const mib2_sctpConnEntry_t	*sp;
5222 	boolean_t		first = B_TRUE;
5223 	mib2_transportMLPEntry_t **attrs, **aptr;
5224 	mib2_transportMLPEntry_t *attr;
5225 
5226 	/*
5227 	 * Preparation pass: the kernel returns separate entries for SCTP
5228 	 * connection table entries and Multilevel Port attributes.  We loop
5229 	 * through the attributes first and set up an array for each address
5230 	 * family.
5231 	 */
5232 	attrs = RSECflag ?
5233 	    gather_attrs(item, MIB2_SCTP, MIB2_SCTP_CONN, sctpEntrySize) :
5234 	    NULL;
5235 
5236 	aptr = attrs;
5237 	head = item;
5238 	for (; item != NULL; item = item->next_item) {
5239 
5240 		if (!(item->group == MIB2_SCTP &&
5241 		    item->mib_id == MIB2_SCTP_CONN))
5242 			continue;
5243 
5244 		for (sp = item->valp;
5245 		    (char *)sp < (char *)item->valp + item->length;
5246 		    /* LINTED: (note 1) */
5247 		    sp = (mib2_sctpConnEntry_t *)((char *)sp + sctpEntrySize)) {
5248 			attr = aptr == NULL ? NULL : *aptr++;
5249 			if (Aflag ||
5250 			    sp->sctpAssocState >= MIB2_SCTP_established) {
5251 				if (first == B_TRUE) {
5252 					(void) puts(sctp_hdr);
5253 					(void) puts(sctp_hdr_normal);
5254 					first = B_FALSE;
5255 				}
5256 				sctp_conn_report_item(head, sp, attr);
5257 			}
5258 		}
5259 	}
5260 	if (attrs != NULL)
5261 		free(attrs);
5262 }
5263 
5264 static char *
5265 plural(int n)
5266 {
5267 	return (n != 1 ? "s" : "");
5268 }
5269 
5270 static char *
5271 pluraly(int n)
5272 {
5273 	return (n != 1 ? "ies" : "y");
5274 }
5275 
5276 static char *
5277 plurales(int n)
5278 {
5279 	return (n != 1 ? "es" : "");
5280 }
5281 
5282 static char *
5283 pktscale(n)
5284 	int n;
5285 {
5286 	static char buf[6];
5287 	char t;
5288 
5289 	if (n < 1024) {
5290 		t = ' ';
5291 	} else if (n < 1024 * 1024) {
5292 		t = 'k';
5293 		n /= 1024;
5294 	} else if (n < 1024 * 1024 * 1024) {
5295 		t = 'm';
5296 		n /= 1024 * 1024;
5297 	} else {
5298 		t = 'g';
5299 		n /= 1024 * 1024 * 1024;
5300 	}
5301 
5302 	(void) snprintf(buf, sizeof (buf), "%4u%c", n, t);
5303 	return (buf);
5304 }
5305 
5306 /* --------------------- mrt_report (netstat -m) -------------------------- */
5307 
5308 static void
5309 mrt_report(mib_item_t *item)
5310 {
5311 	int		jtemp = 0;
5312 	struct vifctl	*vip;
5313 	vifi_t		vifi;
5314 	struct mfcctl	*mfccp;
5315 	int		numvifs = 0;
5316 	int		nmfc = 0;
5317 	char		abuf[MAXHOSTNAMELEN + 1];
5318 
5319 	if (!(family_selected(AF_INET)))
5320 		return;
5321 
5322 	/* 'for' loop 1: */
5323 	for (; item; item = item->next_item) {
5324 		if (Dflag) {
5325 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
5326 			(void) printf("Group = %d, mib_id = %d, "
5327 			    "length = %d, valp = 0x%p\n",
5328 			    item->group, item->mib_id, item->length,
5329 			    item->valp);
5330 		}
5331 		if (item->group != EXPER_DVMRP)
5332 			continue; /* 'for' loop 1 */
5333 
5334 		switch (item->mib_id) {
5335 
5336 		case EXPER_DVMRP_VIF:
5337 			if (Dflag)
5338 				(void) printf("%u records for ipVifTable:\n",
5339 				    item->length/sizeof (struct vifctl));
5340 			if (item->length/sizeof (struct vifctl) == 0) {
5341 				(void) puts("\nVirtual Interface Table is "
5342 				    "empty");
5343 				break;
5344 			}
5345 
5346 			(void) puts("\nVirtual Interface Table\n"
5347 			    " Vif Threshold Rate_Limit Local-Address"
5348 			    "   Remote-Address     Pkt_in   Pkt_out");
5349 
5350 			/* 'for' loop 2: */
5351 			for (vip = (struct vifctl *)item->valp;
5352 			    (char *)vip < (char *)item->valp + item->length;
5353 			    /* LINTED: (note 1) */
5354 			    vip = (struct vifctl *)((char *)vip +
5355 			    vifctlSize)) {
5356 				if (vip->vifc_lcl_addr.s_addr == 0)
5357 					continue; /* 'for' loop 2 */
5358 				/* numvifs = vip->vifc_vifi; */
5359 
5360 				numvifs++;
5361 				(void) printf("  %2u       %3u       "
5362 				    "%4u %-15.15s",
5363 				    vip->vifc_vifi,
5364 				    vip->vifc_threshold,
5365 				    vip->vifc_rate_limit,
5366 				    pr_addr(vip->vifc_lcl_addr.s_addr,
5367 				    abuf, sizeof (abuf)));
5368 				(void) printf(" %-15.15s  %8u  %8u\n",
5369 				    (vip->vifc_flags & VIFF_TUNNEL) ?
5370 				    pr_addr(vip->vifc_rmt_addr.s_addr,
5371 				    abuf, sizeof (abuf)) : "",
5372 				    vip->vifc_pkt_in,
5373 				    vip->vifc_pkt_out);
5374 			} /* 'for' loop 2 ends */
5375 
5376 			(void) printf("Numvifs: %d\n", numvifs);
5377 			break;
5378 
5379 		case EXPER_DVMRP_MRT:
5380 			if (Dflag)
5381 				(void) printf("%u records for ipMfcTable:\n",
5382 					item->length/sizeof (struct vifctl));
5383 			if (item->length/sizeof (struct vifctl) == 0) {
5384 				(void) puts("\nMulticast Forwarding Cache is "
5385 				    "empty");
5386 				break;
5387 			}
5388 
5389 			(void) puts("\nMulticast Forwarding Cache\n"
5390 			    "  Origin-Subnet                 Mcastgroup      "
5391 			    "# Pkts  In-Vif  Out-vifs/Forw-ttl");
5392 
5393 			for (mfccp = (struct mfcctl *)item->valp;
5394 			    (char *)mfccp < (char *)item->valp + item->length;
5395 			    /* LINTED: (note 1) */
5396 			    mfccp = (struct mfcctl *)((char *)mfccp +
5397 			    mfcctlSize)) {
5398 
5399 				nmfc++;
5400 				(void) printf("  %-30.15s",
5401 				    pr_addr(mfccp->mfcc_origin.s_addr,
5402 				    abuf, sizeof (abuf)));
5403 				(void) printf("%-15.15s  %6s  %3u    ",
5404 				    pr_net(mfccp->mfcc_mcastgrp.s_addr,
5405 					mfccp->mfcc_mcastgrp.s_addr,
5406 					abuf, sizeof (abuf)),
5407 				    pktscale((int)mfccp->mfcc_pkt_cnt),
5408 					mfccp->mfcc_parent);
5409 
5410 				for (vifi = 0; vifi < MAXVIFS; ++vifi) {
5411 					if (mfccp->mfcc_ttls[vifi]) {
5412 						(void) printf("      %u (%u)",
5413 						    vifi,
5414 						    mfccp->mfcc_ttls[vifi]);
5415 					}
5416 
5417 				}
5418 				(void) putchar('\n');
5419 			}
5420 			(void) printf("\nTotal no. of entries in cache: %d\n",
5421 			    nmfc);
5422 			break;
5423 		}
5424 	} /* 'for' loop 1 ends */
5425 	(void) putchar('\n');
5426 	(void) fflush(stdout);
5427 }
5428 
5429 /*
5430  * Get the stats for the cache named 'name'.  If prefix != 0, then
5431  * interpret the name as a prefix, and sum up stats for all caches
5432  * named 'name*'.
5433  */
5434 static void
5435 kmem_cache_stats(char *title, char *name, int prefix, int64_t *total_bytes)
5436 {
5437 	int len;
5438 	int alloc;
5439 	int64_t total_alloc = 0;
5440 	int alloc_fail, total_alloc_fail = 0;
5441 	int buf_size = 0;
5442 	int buf_avail;
5443 	int buf_total;
5444 	int buf_max, total_buf_max = 0;
5445 	int buf_inuse, total_buf_inuse = 0;
5446 	kstat_t *ksp;
5447 	char buf[256];
5448 
5449 	len = prefix ? strlen(name) : 256;
5450 
5451 	/* 'for' loop 1: */
5452 	for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
5453 
5454 		if (strcmp(ksp->ks_class, "kmem_cache") != 0)
5455 			continue; /* 'for' loop 1 */
5456 
5457 		/*
5458 		 * Hack alert: because of the way streams messages are
5459 		 * allocated, every constructed free dblk has an associated
5460 		 * mblk.  From the allocator's viewpoint those mblks are
5461 		 * allocated (because they haven't been freed), but from
5462 		 * our viewpoint they're actually free (because they're
5463 		 * not currently in use).  To account for this caching
5464 		 * effect we subtract the total constructed free dblks
5465 		 * from the total allocated mblks to derive mblks in use.
5466 		 */
5467 		if (strcmp(name, "streams_mblk") == 0 &&
5468 		    strncmp(ksp->ks_name, "streams_dblk", 12) == 0) {
5469 			(void) safe_kstat_read(kc, ksp, NULL);
5470 			total_buf_inuse -=
5471 				kstat_named_value(ksp, "buf_constructed");
5472 			continue; /* 'for' loop 1 */
5473 		}
5474 
5475 		if (strncmp(ksp->ks_name, name, len) != 0)
5476 			continue; /* 'for' loop 1 */
5477 
5478 		(void) safe_kstat_read(kc, ksp, NULL);
5479 
5480 		alloc		= kstat_named_value(ksp, "alloc");
5481 		alloc_fail	= kstat_named_value(ksp, "alloc_fail");
5482 		buf_size	= kstat_named_value(ksp, "buf_size");
5483 		buf_avail	= kstat_named_value(ksp, "buf_avail");
5484 		buf_total	= kstat_named_value(ksp, "buf_total");
5485 		buf_max		= kstat_named_value(ksp, "buf_max");
5486 		buf_inuse	= buf_total - buf_avail;
5487 
5488 		if (Vflag && prefix) {
5489 			(void) snprintf(buf, sizeof (buf), "%s%s", title,
5490 			    ksp->ks_name + len);
5491 			(void) printf("    %-18s %6u %9u %11u %11u\n",
5492 			    buf, buf_inuse, buf_max, alloc, alloc_fail);
5493 		}
5494 
5495 		total_alloc		+= alloc;
5496 		total_alloc_fail	+= alloc_fail;
5497 		total_buf_max		+= buf_max;
5498 		total_buf_inuse		+= buf_inuse;
5499 		*total_bytes		+= (int64_t)buf_inuse * buf_size;
5500 	} /* 'for' loop 1 ends */
5501 
5502 	if (buf_size == 0) {
5503 		(void) printf("%-22s [couldn't find statistics for %s]\n",
5504 			title, name);
5505 		return;
5506 	}
5507 
5508 	if (Vflag && prefix)
5509 		(void) snprintf(buf, sizeof (buf), "%s_total", title);
5510 	else
5511 		(void) snprintf(buf, sizeof (buf), "%s", title);
5512 
5513 	(void) printf("%-22s %6d %9d %11lld %11d\n", buf,
5514 		total_buf_inuse, total_buf_max, total_alloc, total_alloc_fail);
5515 }
5516 
5517 static void
5518 m_report(void)
5519 {
5520 	int64_t total_bytes = 0;
5521 
5522 	(void) puts("streams allocation:");
5523 	(void) printf("%63s\n", "cumulative  allocation");
5524 	(void) printf("%63s\n",
5525 	    "current   maximum       total    failures");
5526 
5527 	kmem_cache_stats("streams",
5528 	    "stream_head_cache", 0, &total_bytes);
5529 	kmem_cache_stats("queues", "queue_cache", 0, &total_bytes);
5530 	kmem_cache_stats("mblk", "streams_mblk", 0, &total_bytes);
5531 	kmem_cache_stats("dblk", "streams_dblk", 1, &total_bytes);
5532 	kmem_cache_stats("linkblk", "linkinfo_cache", 0, &total_bytes);
5533 	kmem_cache_stats("syncq", "syncq_cache", 0, &total_bytes);
5534 	kmem_cache_stats("qband", "qband_cache", 0, &total_bytes);
5535 
5536 	(void) printf("\n%lld Kbytes allocated for streams data\n",
5537 		total_bytes / 1024);
5538 
5539 	(void) putchar('\n');
5540 	(void) fflush(stdout);
5541 }
5542 
5543 /* --------------------------------- */
5544 
5545 /*
5546  * Print an IPv4 address. Remove the matching part of the domain name
5547  * from the returned name.
5548  */
5549 static char *
5550 pr_addr(uint_t addr, char *dst, uint_t dstlen)
5551 {
5552 	char			*cp;
5553 	struct hostent		*hp = NULL;
5554 	static char		domain[MAXHOSTNAMELEN + 1];
5555 	static boolean_t	first = B_TRUE;
5556 	int			error_num;
5557 
5558 	if (first) {
5559 		first = B_FALSE;
5560 		if (sysinfo(SI_HOSTNAME, domain, MAXHOSTNAMELEN) != -1 &&
5561 		    (cp = strchr(domain, '.'))) {
5562 			(void) strncpy(domain, cp + 1, sizeof (domain));
5563 		} else
5564 			domain[0] = 0;
5565 	}
5566 	cp = NULL;
5567 	if (!Nflag) {
5568 		hp = getipnodebyaddr((char *)&addr, sizeof (uint_t), AF_INET,
5569 		    &error_num);
5570 		if (hp) {
5571 			if ((cp = strchr(hp->h_name, '.')) != NULL &&
5572 			    strcasecmp(cp + 1, domain) == 0)
5573 				*cp = 0;
5574 			cp = hp->h_name;
5575 		}
5576 	}
5577 	if (cp != NULL) {
5578 		(void) strncpy(dst, cp, dstlen);
5579 		dst[dstlen - 1] = 0;
5580 	} else {
5581 		(void) inet_ntop(AF_INET, (char *)&addr, dst, dstlen);
5582 	}
5583 	if (hp != NULL)
5584 		freehostent(hp);
5585 	return (dst);
5586 }
5587 
5588 /*
5589  * Print a non-zero IPv4 address.  Print "    --" if the address is zero.
5590  */
5591 static char *
5592 pr_addrnz(ipaddr_t addr, char *dst, uint_t dstlen)
5593 {
5594 	if (addr == INADDR_ANY) {
5595 		(void) strlcpy(dst, "    --", dstlen);
5596 		return (dst);
5597 	}
5598 	return (pr_addr(addr, dst, dstlen));
5599 }
5600 
5601 /*
5602  * Print an IPv6 address. Remove the matching part of the domain name
5603  * from the returned name.
5604  */
5605 static char *
5606 pr_addr6(const struct in6_addr *addr, char *dst, uint_t dstlen)
5607 {
5608 	char			*cp;
5609 	struct hostent		*hp = NULL;
5610 	static char		domain[MAXHOSTNAMELEN + 1];
5611 	static boolean_t	first = B_TRUE;
5612 	int			error_num;
5613 
5614 	if (first) {
5615 		first = B_FALSE;
5616 		if (sysinfo(SI_HOSTNAME, domain, MAXHOSTNAMELEN) != -1 &&
5617 		    (cp = strchr(domain, '.'))) {
5618 			(void) strncpy(domain, cp + 1, sizeof (domain));
5619 		} else
5620 			domain[0] = 0;
5621 	}
5622 	cp = NULL;
5623 	if (!Nflag) {
5624 		hp = getipnodebyaddr((char *)addr,
5625 		    sizeof (struct in6_addr), AF_INET6, &error_num);
5626 		if (hp) {
5627 			if ((cp = strchr(hp->h_name, '.')) != NULL &&
5628 			    strcasecmp(cp + 1, domain) == 0)
5629 				*cp = 0;
5630 			cp = hp->h_name;
5631 		}
5632 	}
5633 	if (cp != NULL) {
5634 		(void) strncpy(dst, cp, dstlen);
5635 		dst[dstlen - 1] = 0;
5636 	} else {
5637 		(void) inet_ntop(AF_INET6, (void *)addr, dst, dstlen);
5638 	}
5639 	if (hp != NULL)
5640 		freehostent(hp);
5641 	return (dst);
5642 }
5643 
5644 /* For IPv4 masks */
5645 static char *
5646 pr_mask(uint_t addr, char *dst, uint_t dstlen)
5647 {
5648 	uint8_t	*ip_addr = (uint8_t *)&addr;
5649 
5650 	(void) snprintf(dst, dstlen, "%d.%d.%d.%d",
5651 	    ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3]);
5652 	return (dst);
5653 }
5654 
5655 /*
5656  * For ipv6 masks format is : dest/mask
5657  * Does not print /128 to save space in printout. H flag carries this notion.
5658  */
5659 static char *
5660 pr_prefix6(const struct in6_addr *addr, uint_t prefixlen, char *dst,
5661     uint_t dstlen)
5662 {
5663 	char *cp;
5664 
5665 	if (IN6_IS_ADDR_UNSPECIFIED(addr) && prefixlen == 0) {
5666 		(void) strncpy(dst, "default", dstlen);
5667 		dst[dstlen - 1] = 0;
5668 		return (dst);
5669 	}
5670 
5671 	(void) pr_addr6(addr, dst, dstlen);
5672 	if (prefixlen != IPV6_ABITS) {
5673 		/* How much room is left? */
5674 		cp = strchr(dst, '\0');
5675 		if (dst + dstlen > cp) {
5676 			dstlen -= (cp - dst);
5677 			(void) snprintf(cp, dstlen, "/%d", prefixlen);
5678 		}
5679 	}
5680 	return (dst);
5681 }
5682 
5683 /* Print IPv4 address and port */
5684 static char *
5685 pr_ap(uint_t addr, uint_t port, char *proto,
5686     char *dst, uint_t dstlen)
5687 {
5688 	char *cp;
5689 
5690 	if (addr == INADDR_ANY) {
5691 		(void) strncpy(dst, "      *", dstlen);
5692 		dst[dstlen - 1] = 0;
5693 	} else {
5694 		(void) pr_addr(addr, dst, dstlen);
5695 	}
5696 	/* How much room is left? */
5697 	cp = strchr(dst, '\0');
5698 	if (dst + dstlen > cp + 1) {
5699 		*cp++ = '.';
5700 		dstlen -= (cp - dst);
5701 		dstlen--;
5702 		(void) portname(port, proto, cp, dstlen);
5703 	}
5704 	return (dst);
5705 }
5706 
5707 /* Print IPv6 address and port */
5708 static char *
5709 pr_ap6(const in6_addr_t *addr, uint_t port, char *proto,
5710     char *dst, uint_t dstlen)
5711 {
5712 	char *cp;
5713 
5714 	if (IN6_IS_ADDR_UNSPECIFIED(addr)) {
5715 		(void) strncpy(dst, "      *", dstlen);
5716 		dst[dstlen - 1] = 0;
5717 	} else {
5718 		(void) pr_addr6(addr, dst, dstlen);
5719 	}
5720 	/* How much room is left? */
5721 	cp = strchr(dst, '\0');
5722 	if (dst + dstlen + 1 > cp) {
5723 		*cp++ = '.';
5724 		dstlen -= (cp - dst);
5725 		dstlen--;
5726 		(void) portname(port, proto, cp, dstlen);
5727 	}
5728 	return (dst);
5729 }
5730 
5731 /*
5732  * Return the name of the network whose address is given. The address is
5733  * assumed to be that of a net or subnet, not a host.
5734  */
5735 static char *
5736 pr_net(uint_t addr, uint_t mask, char *dst, uint_t dstlen)
5737 {
5738 	char		*cp = NULL;
5739 	struct netent	*np = NULL;
5740 	struct hostent	*hp = NULL;
5741 	uint_t		net;
5742 	int		subnetshift;
5743 	int		error_num;
5744 
5745 	if (addr == INADDR_ANY && mask == INADDR_ANY) {
5746 		(void) strncpy(dst, "default", dstlen);
5747 		dst[dstlen - 1] = 0;
5748 		return (dst);
5749 	}
5750 
5751 	if (!Nflag && addr) {
5752 		if (mask == 0) {
5753 			if (IN_CLASSA(addr)) {
5754 				mask = (uint_t)IN_CLASSA_NET;
5755 				subnetshift = 8;
5756 			} else if (IN_CLASSB(addr)) {
5757 				mask = (uint_t)IN_CLASSB_NET;
5758 				subnetshift = 8;
5759 			} else {
5760 				mask = (uint_t)IN_CLASSC_NET;
5761 				subnetshift = 4;
5762 			}
5763 			/*
5764 			 * If there are more bits than the standard mask
5765 			 * would suggest, subnets must be in use. Guess at
5766 			 * the subnet mask, assuming reasonable width subnet
5767 			 * fields.
5768 			 */
5769 			while (addr & ~mask)
5770 				/* compiler doesn't sign extend! */
5771 				mask = (mask | ((int)mask >> subnetshift));
5772 		}
5773 		net = addr & mask;
5774 		while ((mask & 1) == 0)
5775 			mask >>= 1, net >>= 1;
5776 		np = getnetbyaddr(net, AF_INET);
5777 		if (np && np->n_net == net)
5778 			cp = np->n_name;
5779 		else {
5780 			/*
5781 			 * Look for subnets in hosts map.
5782 			 */
5783 			hp = getipnodebyaddr((char *)&addr, sizeof (uint_t),
5784 			    AF_INET, &error_num);
5785 			if (hp)
5786 				cp = hp->h_name;
5787 		}
5788 	}
5789 	if (cp != NULL) {
5790 		(void) strncpy(dst, cp, dstlen);
5791 		dst[dstlen - 1] = 0;
5792 	} else {
5793 		(void) inet_ntop(AF_INET, (char *)&addr, dst, dstlen);
5794 	}
5795 	if (hp != NULL)
5796 		freehostent(hp);
5797 	return (dst);
5798 }
5799 
5800 /*
5801  * Return the name of the network whose address is given.
5802  * The address is assumed to be a host address.
5803  */
5804 static char *
5805 pr_netaddr(uint_t addr, uint_t mask, char *dst, uint_t dstlen)
5806 {
5807 	char		*cp = NULL;
5808 	struct netent	*np = NULL;
5809 	struct hostent	*hp = NULL;
5810 	uint_t		net;
5811 	uint_t		netshifted;
5812 	int		subnetshift;
5813 	struct in_addr in;
5814 	int		error_num;
5815 	uint_t		nbo_addr = addr;	/* network byte order */
5816 
5817 	addr = ntohl(addr);
5818 	mask = ntohl(mask);
5819 	if (addr == INADDR_ANY && mask == INADDR_ANY) {
5820 		(void) strncpy(dst, "default", dstlen);
5821 		dst[dstlen - 1] = 0;
5822 		return (dst);
5823 	}
5824 
5825 	/* Figure out network portion of address (with host portion = 0) */
5826 	if (addr) {
5827 		/* Try figuring out mask if unknown (all 0s). */
5828 		if (mask == 0) {
5829 			if (IN_CLASSA(addr)) {
5830 				mask = (uint_t)IN_CLASSA_NET;
5831 				subnetshift = 8;
5832 			} else if (IN_CLASSB(addr)) {
5833 				mask = (uint_t)IN_CLASSB_NET;
5834 				subnetshift = 8;
5835 			} else {
5836 				mask = (uint_t)IN_CLASSC_NET;
5837 				subnetshift = 4;
5838 			}
5839 			/*
5840 			 * If there are more bits than the standard mask
5841 			 * would suggest, subnets must be in use. Guess at
5842 			 * the subnet mask, assuming reasonable width subnet
5843 			 * fields.
5844 			 */
5845 			while (addr & ~mask)
5846 				/* compiler doesn't sign extend! */
5847 				mask = (mask | ((int)mask >> subnetshift));
5848 		}
5849 		net = netshifted = addr & mask;
5850 		while ((mask & 1) == 0)
5851 			mask >>= 1, netshifted >>= 1;
5852 	}
5853 	else
5854 		net = netshifted = 0;
5855 
5856 	/* Try looking up name unless -n was specified. */
5857 	if (!Nflag) {
5858 		np = getnetbyaddr(netshifted, AF_INET);
5859 		if (np && np->n_net == netshifted)
5860 			cp = np->n_name;
5861 		else {
5862 			/*
5863 			 * Look for subnets in hosts map.
5864 			 */
5865 			hp = getipnodebyaddr((char *)&nbo_addr, sizeof (uint_t),
5866 			    AF_INET, &error_num);
5867 			if (hp)
5868 				cp = hp->h_name;
5869 		}
5870 
5871 		if (cp != NULL) {
5872 			(void) strncpy(dst, cp, dstlen);
5873 			dst[dstlen - 1] = 0;
5874 			if (hp != NULL)
5875 				freehostent(hp);
5876 			return (dst);
5877 		}
5878 		/*
5879 		 * No name found for net: fallthru and return in decimal
5880 		 * dot notation.
5881 		 */
5882 	}
5883 
5884 	in.s_addr = htonl(net);
5885 	(void) inet_ntop(AF_INET, (char *)&in, dst, dstlen);
5886 	if (hp != NULL)
5887 		freehostent(hp);
5888 	return (dst);
5889 }
5890 
5891 /*
5892  * Return the filter mode as a string:
5893  *	1 => "INCLUDE"
5894  *	2 => "EXCLUDE"
5895  *	otherwise "<unknown>"
5896  */
5897 static char *
5898 fmodestr(uint_t fmode)
5899 {
5900 	switch (fmode) {
5901 	case 1:
5902 		return ("INCLUDE");
5903 	case 2:
5904 		return ("EXCLUDE");
5905 	default:
5906 		return ("<unknown>");
5907 	}
5908 }
5909 
5910 #define	MAX_STRING_SIZE	256
5911 
5912 static const char *
5913 pr_secattr(const sec_attr_list_t *attrs)
5914 {
5915 	int i;
5916 	char buf[MAX_STRING_SIZE + 1], *cp;
5917 	static char *sbuf;
5918 	static size_t sbuf_len;
5919 	struct rtsa_s rtsa;
5920 	const sec_attr_list_t *aptr;
5921 
5922 	if (!RSECflag || attrs == NULL)
5923 		return ("");
5924 
5925 	for (aptr = attrs, i = 1; aptr != NULL; aptr = aptr->sal_next)
5926 		i += MAX_STRING_SIZE;
5927 	if (i > sbuf_len) {
5928 		cp = realloc(sbuf, i);
5929 		if (cp == NULL) {
5930 			perror("realloc security attribute buffer");
5931 			return ("");
5932 		}
5933 		sbuf_len = i;
5934 		sbuf = cp;
5935 	}
5936 
5937 	cp = sbuf;
5938 	while (attrs != NULL) {
5939 		const mib2_ipAttributeEntry_t *iae = attrs->sal_attr;
5940 
5941 		/* note: effectively hard-coded in rtsa_keyword */
5942 		rtsa.rtsa_mask = RTSA_CIPSO | RTSA_SLRANGE | RTSA_DOI;
5943 		rtsa.rtsa_slrange = iae->iae_slrange;
5944 		rtsa.rtsa_doi = iae->iae_doi;
5945 
5946 		(void) snprintf(cp, MAX_STRING_SIZE,
5947 		    "<%s>%s ", rtsa_to_str(&rtsa, buf, sizeof (buf)),
5948 		    attrs->sal_next == NULL ? "" : ",");
5949 		cp += strlen(cp);
5950 		attrs = attrs->sal_next;
5951 	}
5952 	*cp = '\0';
5953 
5954 	return (sbuf);
5955 }
5956 
5957 /*
5958  * Pretty print a port number. If the Nflag was
5959  * specified, use numbers instead of names.
5960  */
5961 static char *
5962 portname(uint_t port, char *proto, char *dst, uint_t dstlen)
5963 {
5964 	struct servent *sp = NULL;
5965 
5966 	if (!Nflag && port)
5967 		sp = getservbyport(htons(port), proto);
5968 	if (sp || port == 0)
5969 		(void) snprintf(dst, dstlen, "%.*s", MAXHOSTNAMELEN,
5970 				sp ? sp->s_name : "*");
5971 	else
5972 		(void) snprintf(dst, dstlen, "%d", port);
5973 	dst[dstlen - 1] = 0;
5974 	return (dst);
5975 }
5976 
5977 /*PRINTFLIKE2*/
5978 void
5979 fail(int do_perror, char *message, ...)
5980 {
5981 	va_list args;
5982 
5983 	va_start(args, message);
5984 	(void) fputs("netstat: ", stderr);
5985 	(void) vfprintf(stderr, message, args);
5986 	va_end(args);
5987 	if (do_perror)
5988 		(void) fprintf(stderr, ": %s", strerror(errno));
5989 	(void) fputc('\n', stderr);
5990 	exit(2);
5991 }
5992 
5993 /*
5994  * Return value of named statistic for given kstat_named kstat;
5995  * return 0LL if named statistic is not in list (use "ll" as a
5996  * type qualifier when printing 64-bit int's with printf() )
5997  */
5998 static uint64_t
5999 kstat_named_value(kstat_t *ksp, char *name)
6000 {
6001 	kstat_named_t *knp;
6002 	uint64_t value;
6003 
6004 	if (ksp == NULL)
6005 		return (0LL);
6006 
6007 	knp = kstat_data_lookup(ksp, name);
6008 	if (knp == NULL)
6009 		return (0LL);
6010 
6011 	switch (knp->data_type) {
6012 	case KSTAT_DATA_INT32:
6013 	case KSTAT_DATA_UINT32:
6014 		value = (uint64_t)(knp->value.ui32);
6015 		break;
6016 	case KSTAT_DATA_INT64:
6017 	case KSTAT_DATA_UINT64:
6018 		value = knp->value.ui64;
6019 		break;
6020 	default:
6021 		value = 0LL;
6022 		break;
6023 	}
6024 
6025 	return (value);
6026 }
6027 
6028 kid_t
6029 safe_kstat_read(kstat_ctl_t *kc, kstat_t *ksp, void *data)
6030 {
6031 	kid_t kstat_chain_id = kstat_read(kc, ksp, data);
6032 
6033 	if (kstat_chain_id == -1)
6034 		fail(1, "kstat_read(%p, '%s') failed", (void *)kc,
6035 		    ksp->ks_name);
6036 	return (kstat_chain_id);
6037 }
6038 
6039 /*
6040  * Parse a list of IRE flag characters into a bit field.
6041  */
6042 static uint_t
6043 flag_bits(const char *arg)
6044 {
6045 	const char *cp;
6046 	uint_t val;
6047 
6048 	if (*arg == '\0')
6049 		fatal(1, "missing flag list\n");
6050 
6051 	val = 0;
6052 	while (*arg != '\0') {
6053 		if ((cp = strchr(flag_list, *arg)) == NULL)
6054 			fatal(1, "%c: illegal flag\n", *arg);
6055 		val |= 1 << (cp - flag_list);
6056 		arg++;
6057 	}
6058 	return (val);
6059 }
6060 
6061 /*
6062  * Handle -f argument.  Validate input format, sort by keyword, and
6063  * save off digested results.
6064  */
6065 static void
6066 process_filter(char *arg)
6067 {
6068 	int idx;
6069 	int klen = 0;
6070 	char *cp, *cp2;
6071 	int val;
6072 	filter_t *newf;
6073 	struct hostent *hp;
6074 	int error_num;
6075 	uint8_t *ucp;
6076 	int maxv;
6077 
6078 	/* Look up the keyword first */
6079 	if (strchr(arg, ':') == NULL) {
6080 		idx = FK_AF;
6081 	} else {
6082 		for (idx = 0; idx < NFILTERKEYS; idx++) {
6083 			klen = strlen(filter_keys[idx]);
6084 			if (strncmp(filter_keys[idx], arg, klen) == 0 &&
6085 			    arg[klen] == ':')
6086 				break;
6087 		}
6088 		if (idx >= NFILTERKEYS)
6089 			fatal(1, "%s: unknown filter keyword\n", arg);
6090 
6091 		/* Advance past keyword and separator. */
6092 		arg += klen + 1;
6093 	}
6094 
6095 	if ((newf = malloc(sizeof (*newf))) == NULL) {
6096 		perror("filter");
6097 		exit(1);
6098 	}
6099 	switch (idx) {
6100 	case FK_AF:
6101 		if (strcmp(arg, "inet") == 0) {
6102 			newf->u.f_family = AF_INET;
6103 		} else if (strcmp(arg, "inet6") == 0) {
6104 			newf->u.f_family = AF_INET6;
6105 		} else if (strcmp(arg, "unix") == 0) {
6106 			newf->u.f_family = AF_UNIX;
6107 		} else {
6108 			newf->u.f_family = strtol(arg, &cp, 0);
6109 			if (arg == cp || *cp != '\0')
6110 				fatal(1, "%s: unknown address family.\n", arg);
6111 		}
6112 		break;
6113 
6114 	case FK_OUTIF:
6115 		if (strcmp(arg, "none") == 0) {
6116 			newf->u.f_ifname = NULL;
6117 			break;
6118 		}
6119 		if (strcmp(arg, "any") == 0) {
6120 			newf->u.f_ifname = "";
6121 			break;
6122 		}
6123 		val = strtol(arg, &cp, 0);
6124 		if (val <= 0 || arg == cp || cp[0] != '\0') {
6125 			if ((val = if_nametoindex(arg)) == 0) {
6126 				perror(arg);
6127 				exit(1);
6128 			}
6129 		}
6130 		newf->u.f_ifname = arg;
6131 		break;
6132 
6133 	case FK_DST:
6134 		V4MASK_TO_V6(IP_HOST_MASK, newf->u.a.f_mask);
6135 		if (strcmp(arg, "any") == 0) {
6136 			/* Special semantics; any address *but* zero */
6137 			newf->u.a.f_address = NULL;
6138 			(void) memset(&newf->u.a.f_mask, 0,
6139 			    sizeof (newf->u.a.f_mask));
6140 			break;
6141 		}
6142 		if (strcmp(arg, "none") == 0) {
6143 			newf->u.a.f_address = NULL;
6144 			break;
6145 		}
6146 		if ((cp = strrchr(arg, '/')) != NULL)
6147 			*cp++ = '\0';
6148 		hp = getipnodebyname(arg, AF_INET6, AI_V4MAPPED|AI_ALL,
6149 		    &error_num);
6150 		if (hp == NULL)
6151 			fatal(1, "%s: invalid or unknown host address\n", arg);
6152 		newf->u.a.f_address = hp;
6153 		if (cp == NULL) {
6154 			V4MASK_TO_V6(IP_HOST_MASK, newf->u.a.f_mask);
6155 		} else {
6156 			val = strtol(cp, &cp2, 0);
6157 			if (cp != cp2 && cp2[0] == '\0') {
6158 				/*
6159 				 * If decode as "/n" works, then translate
6160 				 * into a mask.
6161 				 */
6162 				if (hp->h_addr_list[0] != NULL &&
6163 				    /* LINTED: (note 1) */
6164 				    IN6_IS_ADDR_V4MAPPED((in6_addr_t
6165 					*)hp->h_addr_list[0])) {
6166 					maxv = IP_ABITS;
6167 				} else {
6168 					maxv = IPV6_ABITS;
6169 				}
6170 				if (val < 0 || val >= maxv)
6171 					fatal(1, "%d: not in range 0 to %d\n",
6172 					    val, maxv - 1);
6173 				if (maxv == IP_ABITS)
6174 					val += IPV6_ABITS - IP_ABITS;
6175 				ucp = newf->u.a.f_mask.s6_addr;
6176 				while (val >= 8)
6177 					*ucp++ = 0xff, val -= 8;
6178 				*ucp++ = (0xff << (8 - val)) & 0xff;
6179 				while (ucp < newf->u.a.f_mask.s6_addr +
6180 				    sizeof (newf->u.a.f_mask.s6_addr))
6181 					*ucp++ = 0;
6182 				/* Otherwise, try as numeric address */
6183 			} else if (inet_pton(AF_INET6,
6184 			    cp, &newf->u.a.f_mask) <= 0) {
6185 				fatal(1, "%s: illegal mask format\n", cp);
6186 			}
6187 		}
6188 		break;
6189 
6190 	case FK_FLAGS:
6191 		if (*arg == '+') {
6192 			newf->u.f.f_flagset = flag_bits(arg + 1);
6193 			newf->u.f.f_flagclear = 0;
6194 		} else if (*arg == '-') {
6195 			newf->u.f.f_flagset = 0;
6196 			newf->u.f.f_flagclear = flag_bits(arg + 1);
6197 		} else {
6198 			newf->u.f.f_flagset = flag_bits(arg);
6199 			newf->u.f.f_flagclear = ~newf->u.f.f_flagset;
6200 		}
6201 		break;
6202 
6203 	default:
6204 		assert(0);
6205 	}
6206 	newf->f_next = filters[idx];
6207 	filters[idx] = newf;
6208 }
6209 
6210 /* Determine if user wants this address family printed. */
6211 static boolean_t
6212 family_selected(int family)
6213 {
6214 	const filter_t *fp;
6215 
6216 	if (v4compat && family == AF_INET6)
6217 		return (B_FALSE);
6218 	if ((fp = filters[FK_AF]) == NULL)
6219 		return (B_TRUE);
6220 	while (fp != NULL) {
6221 		if (fp->u.f_family == family)
6222 			return (B_TRUE);
6223 		fp = fp->f_next;
6224 	}
6225 	return (B_FALSE);
6226 }
6227 
6228 /*
6229  * print the usage line
6230  */
6231 static void
6232 usage(char *cmdname)
6233 {
6234 	(void) fprintf(stderr, "usage: %s [-anv] [-f address_family]\n",
6235 	    cmdname);
6236 	(void) fprintf(stderr, "       %s [-n] [-f address_family] "
6237 	    "[-P protocol] [-g | -p | -s [interval [count]]]\n", cmdname);
6238 	(void) fprintf(stderr, "       %s -m [-v] "
6239 	    "[interval [count]]\n", cmdname);
6240 	(void) fprintf(stderr, "       %s -i [-I interface] [-an] "
6241 	    "[-f address_family] [interval [count]]\n", cmdname);
6242 	(void) fprintf(stderr, "       %s -r [-anv] "
6243 	    "[-f address_family|filter]\n", cmdname);
6244 	(void) fprintf(stderr, "       %s -M [-ns] [-f address_family]\n",
6245 	    cmdname);
6246 	(void) fprintf(stderr, "       %s -D [-I interface] "
6247 	    "[-f address_family]\n", cmdname);
6248 	exit(EXIT_FAILURE);
6249 }
6250 
6251 /*
6252  * fatal: print error message to stderr and
6253  * call exit(errcode)
6254  */
6255 /*PRINTFLIKE2*/
6256 static void
6257 fatal(int errcode, char *format, ...)
6258 {
6259 	va_list argp;
6260 
6261 	if (format == NULL)
6262 		return;
6263 
6264 	va_start(argp, format);
6265 	(void) vfprintf(stderr, format, argp);
6266 	va_end(argp);
6267 
6268 	exit(errcode);
6269 }
6270