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