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