xref: /illumos-gate/usr/src/cmd/cmd-inet/usr.bin/netstat/netstat.c (revision c559157643fef9f9afb0414e00a3579407ba3052)
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 (c) 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 1990  Mentat Inc.
24  * netstat.c 2.2, last change 9/9/91
25  * MROUTING Revision 3.5
26  * Copyright 2018, Joyent, Inc.
27  * Copyright 2020 OmniOS Community Edition (OmniOSce) Association.
28  */
29 
30 /*
31  * simple netstat based on snmp/mib-2 interface to the TCP/IP stack
32  *
33  * TODO:
34  *	Add ability to request subsets from kernel (with level = MIB2_IP;
35  *	name = 0 meaning everything for compatibility)
36  */
37 
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <stdarg.h>
41 #include <unistd.h>
42 #include <strings.h>
43 #include <string.h>
44 #include <errno.h>
45 #include <ctype.h>
46 #include <kstat.h>
47 #include <assert.h>
48 #include <locale.h>
49 #include <synch.h>
50 #include <thread.h>
51 #include <pwd.h>
52 #include <limits.h>
53 #include <sys/ccompile.h>
54 
55 #include <sys/types.h>
56 #include <sys/stat.h>
57 #include <sys/stream.h>
58 #include <stropts.h>
59 #include <sys/strstat.h>
60 #include <sys/tihdr.h>
61 #include <procfs.h>
62 #include <dirent.h>
63 
64 #include <sys/socket.h>
65 #include <sys/socketvar.h>
66 #include <sys/sockio.h>
67 #include <netinet/in.h>
68 #include <net/if.h>
69 #include <net/route.h>
70 
71 #include <inet/mib2.h>
72 #include <inet/ip.h>
73 #include <inet/arp.h>
74 #include <inet/tcp.h>
75 #include <netinet/igmp_var.h>
76 #include <netinet/ip_mroute.h>
77 
78 #include <arpa/inet.h>
79 #include <netdb.h>
80 #include <fcntl.h>
81 #include <sys/systeminfo.h>
82 #include <arpa/inet.h>
83 
84 #include <netinet/dhcp.h>
85 #include <dhcpagent_ipc.h>
86 #include <dhcpagent_util.h>
87 #include <compat.h>
88 #include <sys/mkdev.h>
89 
90 #include <libtsnet.h>
91 #include <tsol/label.h>
92 
93 #include <libproc.h>
94 
95 #include "statcommon.h"
96 
97 #define	STR_EXPAND	4
98 
99 #define	V4MASK_TO_V6(v4, v6)	((v6)._S6_un._S6_u32[0] = 0xfffffffful, \
100 				(v6)._S6_un._S6_u32[1] = 0xfffffffful, \
101 				(v6)._S6_un._S6_u32[2] = 0xfffffffful, \
102 				(v6)._S6_un._S6_u32[3] = (v4))
103 
104 #define	IN6_IS_V4MASK(v6)	((v6)._S6_un._S6_u32[0] == 0xfffffffful && \
105 				(v6)._S6_un._S6_u32[1] == 0xfffffffful && \
106 				(v6)._S6_un._S6_u32[2] == 0xfffffffful)
107 
108 /*
109  * This is used as a cushion in the buffer allocation directed by SIOCGLIFNUM.
110  * Because there's no locking between SIOCGLIFNUM and SIOCGLIFCONF, it's
111  * possible for an administrator to plumb new interfaces between those two
112  * calls, resulting in the failure of the latter.  This addition makes that
113  * less likely.
114  */
115 #define	LIFN_GUARD_VALUE	10
116 
117 typedef struct mib_item_s {
118 	struct mib_item_s	*next_item;
119 	int			group;
120 	int			mib_id;
121 	int			length;
122 	void			*valp;
123 } mib_item_t;
124 
125 struct	ifstat {
126 	uint64_t	ipackets;
127 	uint64_t	ierrors;
128 	uint64_t	opackets;
129 	uint64_t	oerrors;
130 	uint64_t	collisions;
131 };
132 
133 struct iflist {
134 	struct iflist	*next_if;
135 	char		ifname[LIFNAMSIZ];
136 	struct ifstat	tot;
137 };
138 
139 static void fatal(int, char *, ...) __NORETURN;
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, mib_item_t *item2);
147 static void		mib_item_destroy(mib_item_t **item);
148 
149 static boolean_t	octetstrmatch(const Octet_t *a, const Octet_t *b);
150 static char		*octetstr(const Octet_t *op, int code,
151 			    char *dst, uint_t dstlen);
152 static char		*pr_addr(uint_t addr, char *dst, uint_t dstlen);
153 static char		*pr_addrnz(ipaddr_t addr, char *dst, uint_t dstlen);
154 static char		*pr_addr6(const in6_addr_t *addr,
155 			    char *dst, uint_t dstlen);
156 static char		*pr_mask(uint_t addr, char *dst, uint_t dstlen);
157 static char		*pr_prefix6(const struct in6_addr *addr,
158 			    uint_t prefixlen, char *dst, uint_t dstlen);
159 static char		*pr_ap(uint_t addr, uint_t port,
160 			    char *proto, char *dst, uint_t dstlen);
161 static char		*pr_ap6(const in6_addr_t *addr, uint_t port,
162 			    char *proto, char *dst, uint_t dstlen);
163 static char		*pr_net(uint_t addr, uint_t mask,
164 			    char *dst, uint_t dstlen);
165 static char		*pr_netaddr(uint_t addr, uint_t mask,
166 			    char *dst, uint_t dstlen);
167 static char		*fmodestr(uint_t fmode);
168 static char		*portname(uint_t port, char *proto,
169 			    char *dst, uint_t dstlen);
170 
171 static const char	*mitcp_state(int code,
172 			    const mib2_transportMLPEntry_t *attr);
173 static const char	*miudp_state(int code,
174 			    const mib2_transportMLPEntry_t *attr);
175 
176 static void		stat_report(mib_item_t *item);
177 static void		mrt_stat_report(mib_item_t *item);
178 static void		arp_report(mib_item_t *item);
179 static void		ndp_report(mib_item_t *item);
180 static void		mrt_report(mib_item_t *item);
181 static void		if_stat_total(struct ifstat *oldstats,
182 			    struct ifstat *newstats, struct ifstat *sumstats);
183 static void		if_report(mib_item_t *item, char *ifname,
184 			    int Iflag_only, boolean_t once_only);
185 static void		if_report_ip4(mib2_ipAddrEntry_t *ap,
186 			    char ifname[], char logintname[],
187 			    struct ifstat *statptr, boolean_t ksp_not_null);
188 static void		if_report_ip6(mib2_ipv6AddrEntry_t *ap6,
189 			    char ifname[], char logintname[],
190 			    struct ifstat *statptr, boolean_t ksp_not_null);
191 static void		ire_report(const mib_item_t *item);
192 static void		tcp_report(const mib_item_t *item);
193 static void		udp_report(const mib_item_t *item);
194 static void		uds_report(kstat_ctl_t *);
195 static void		group_report(mib_item_t *item);
196 static void		dce_report(mib_item_t *item);
197 static void		print_ip_stats(mib2_ip_t *ip);
198 static void		print_icmp_stats(mib2_icmp_t *icmp);
199 static void		print_ip6_stats(mib2_ipv6IfStatsEntry_t *ip6);
200 static void		print_icmp6_stats(mib2_ipv6IfIcmpEntry_t *icmp6);
201 static void		print_sctp_stats(mib2_sctp_t *tcp);
202 static void		print_tcp_stats(mib2_tcp_t *tcp);
203 static void		print_udp_stats(mib2_udp_t *udp);
204 static void		print_rawip_stats(mib2_rawip_t *rawip);
205 static void		print_igmp_stats(struct igmpstat *igps);
206 static void		print_mrt_stats(struct mrtstat *mrts);
207 static void		sctp_report(const mib_item_t *item);
208 static void		sum_ip6_stats(mib2_ipv6IfStatsEntry_t *ip6,
209 			    mib2_ipv6IfStatsEntry_t *sum6);
210 static void		sum_icmp6_stats(mib2_ipv6IfIcmpEntry_t *icmp6,
211 			    mib2_ipv6IfIcmpEntry_t *sum6);
212 static void		m_report(void);
213 static void		dhcp_report(char *);
214 
215 static	uint64_t	kstat_named_value(kstat_t *, char *);
216 static	kid_t		safe_kstat_read(kstat_ctl_t *, kstat_t *, void *);
217 static int		isnum(char *);
218 static char		*plural(int n);
219 static char		*pluraly(int n);
220 static char		*plurales(int n);
221 static void		process_filter(char *arg);
222 static char		*ifindex2str(uint_t, char *);
223 static boolean_t	family_selected(int family);
224 
225 static void		usage(char *);
226 static char		*get_username(uid_t);
227 
228 static void		process_hash_build(void);
229 static void		process_hash_free(void);
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 static	boolean_t	Aflag = B_FALSE;	/* All sockets/ifs/rtng-tbls */
239 static	boolean_t	CIDRflag = B_FALSE;	/* CIDR for IPv4 -i/-r addrs */
240 static	boolean_t	Dflag = B_FALSE;	/* DCE 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	Uflag = B_FALSE;	/* Show PID and UID info. */
249 static	boolean_t	Pflag = B_FALSE;	/* Net to Media Tables */
250 static	boolean_t	Gflag = B_FALSE;	/* Multicast group membership */
251 static	boolean_t	MMflag = B_FALSE;	/* Multicast routing table */
252 static	boolean_t	DHCPflag = B_FALSE;	/* DHCP statistics */
253 static	boolean_t	Xflag = B_FALSE;	/* Debug Info */
254 
255 static	int	v4compat = 0;	/* Compatible printing format for status */
256 
257 static int	proto = IPPROTO_MAX;	/* all protocols */
258 kstat_ctl_t	*kc = NULL;
259 
260 /*
261  * Name service timeout detection constants.
262  */
263 static mutex_t ns_lock = ERRORCHECKMUTEX;
264 static boolean_t ns_active = B_FALSE;	/* Is a lookup ongoing? */
265 static hrtime_t ns_starttime;		/* Time the lookup started */
266 static int ns_sleeptime = 2;		/* Time in seconds between checks */
267 static int ns_warntime = 2;		/* Time in seconds before warning */
268 
269 /*
270  * Sizes of data structures extracted from the base mib.
271  * This allows the size of the tables entries to grow while preserving
272  * binary compatibility.
273  */
274 static int ipAddrEntrySize;
275 static int ipRouteEntrySize;
276 static int ipNetToMediaEntrySize;
277 static int ipMemberEntrySize;
278 static int ipGroupSourceEntrySize;
279 static int ipRouteAttributeSize;
280 static int vifctlSize;
281 static int mfcctlSize;
282 
283 static int ipv6IfStatsEntrySize;
284 static int ipv6IfIcmpEntrySize;
285 static int ipv6AddrEntrySize;
286 static int ipv6RouteEntrySize;
287 static int ipv6NetToMediaEntrySize;
288 static int ipv6MemberEntrySize;
289 static int ipv6GroupSourceEntrySize;
290 
291 static int ipDestEntrySize;
292 
293 static int transportMLPSize;
294 static int tcpConnEntrySize;
295 static int tcp6ConnEntrySize;
296 static int udpEntrySize;
297 static int udp6EntrySize;
298 static int sctpEntrySize;
299 static int sctpLocalEntrySize;
300 static int sctpRemoteEntrySize;
301 
302 #define	protocol_selected(p)	(proto == IPPROTO_MAX || proto == (p))
303 
304 /* Machinery used for -f (filter) option */
305 enum { FK_AF = 0, FK_OUTIF, FK_DST, FK_FLAGS, NFILTERKEYS };
306 
307 static const char *filter_keys[NFILTERKEYS] = {
308 	"af", "outif", "dst", "flags"
309 };
310 
311 static m_label_t *zone_security_label = NULL;
312 
313 /* Flags on routes */
314 #define	FLF_A		0x00000001
315 #define	FLF_b		0x00000002
316 #define	FLF_D		0x00000004
317 #define	FLF_G		0x00000008
318 #define	FLF_H		0x00000010
319 #define	FLF_L		0x00000020
320 #define	FLF_U		0x00000040
321 #define	FLF_M		0x00000080
322 #define	FLF_S		0x00000100
323 #define	FLF_C		0x00000200	/* IRE_IF_CLONE */
324 #define	FLF_I		0x00000400	/* RTF_INDIRECT */
325 #define	FLF_R		0x00000800	/* RTF_REJECT */
326 #define	FLF_B		0x00001000	/* RTF_BLACKHOLE */
327 #define	FLF_Z		0x00100000	/* RTF_ZONE */
328 
329 static const char flag_list[] = "AbDGHLUMSCIRBZ";
330 
331 typedef struct filter_rule filter_t;
332 
333 struct filter_rule {
334 	filter_t *f_next;
335 	union {
336 		int f_family;
337 		const char *f_ifname;
338 		struct {
339 			struct hostent *f_address;
340 			in6_addr_t f_mask;
341 		} a;
342 		struct {
343 			uint_t f_flagset;
344 			uint_t f_flagclear;
345 		} f;
346 	} u;
347 };
348 
349 /*
350  * The user-specified filters are linked into lists separated by
351  * keyword (type of filter).  Thus, the matching algorithm is:
352  *	For each non-empty filter list
353  *		If no filters in the list match
354  *			then stop here; route doesn't match
355  *	If loop above completes, then route does match and will be
356  *	displayed.
357  */
358 static filter_t *filters[NFILTERKEYS];
359 
360 static uint_t timestamp_fmt = NODATE;
361 
362 #if !defined(TEXT_DOMAIN)		/* Should be defined by cc -D */
363 #define	TEXT_DOMAIN "SYS_TEST"		/* Use this only if it isn't */
364 #endif
365 
366 static void
367 ns_lookup_start(void)
368 {
369 	mutex_enter(&ns_lock);
370 	ns_active = B_TRUE;
371 	ns_starttime = gethrtime();
372 	mutex_exit(&ns_lock);
373 }
374 
375 static void
376 ns_lookup_end(void)
377 {
378 	mutex_enter(&ns_lock);
379 	ns_active = B_FALSE;
380 	mutex_exit(&ns_lock);
381 }
382 
383 /*
384  * When name services are not functioning, this program appears to hang to the
385  * user. To try and give the user a chance of figuring out that this might be
386  * the case, we end up warning them and suggest that they may want to use the -n
387  * flag.
388  */
389 /* ARGSUSED */
390 static void *
391 ns_warning_thr(void *unsued)
392 {
393 	for (;;) {
394 		hrtime_t now;
395 
396 		(void) sleep(ns_sleeptime);
397 		now = gethrtime();
398 		mutex_enter(&ns_lock);
399 		if (ns_active && now - ns_starttime >= ns_warntime * NANOSEC) {
400 			(void) fprintf(stderr, "warning: data "
401 			    "available, but name service lookups are "
402 			    "taking a while. Use the -n option to "
403 			    "disable name service lookups.\n");
404 			mutex_exit(&ns_lock);
405 			return (NULL);
406 		}
407 		mutex_exit(&ns_lock);
408 	}
409 
410 	return (NULL);
411 }
412 
413 int
414 main(int argc, char **argv)
415 {
416 	char		*name;
417 	mib_item_t	*item = NULL;
418 	mib_item_t	*previtem = NULL;
419 	int		sd = -1;
420 	char	*ifname = NULL;
421 	int	interval = 0;	/* Single time by default */
422 	int	count = -1;	/* Forever */
423 	int	c;
424 	int	d;
425 	/*
426 	 * Possible values of 'Iflag_only':
427 	 * -1, no feature-flags;
428 	 *  0, IFlag and other feature-flags enabled
429 	 *  1, IFlag is the only feature-flag enabled
430 	 * : trinary variable, modified using IFLAGMOD()
431 	 */
432 	int Iflag_only = -1;
433 	boolean_t once_only = B_FALSE; /* '-i' with count > 1 */
434 	extern char	*optarg;
435 	extern int	optind;
436 	char *default_ip_str = NULL;
437 
438 	name = argv[0];
439 
440 	v4compat = get_compat_flag(&default_ip_str);
441 	if (v4compat == DEFAULT_PROT_BAD_VALUE)
442 		fatal(2, "%s: %s: Bad value for %s in %s\n", name,
443 		    default_ip_str, DEFAULT_IP, INET_DEFAULT_FILE);
444 	free(default_ip_str);
445 
446 	(void) setlocale(LC_ALL, "");
447 	(void) textdomain(TEXT_DOMAIN);
448 
449 	while ((c = getopt(argc, argv, "acdimnrspMguvxf:P:I:DRT:")) != -1) {
450 		switch ((char)c) {
451 		case 'a':		/* all connections */
452 			Aflag = B_TRUE;
453 			break;
454 
455 		case 'c':
456 			CIDRflag = B_TRUE;
457 			break;
458 
459 		case 'd':		/* DCE info */
460 			Dflag = B_TRUE;
461 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
462 			break;
463 
464 		case 'i':		/* interface (ill/ipif report) */
465 			Iflag = B_TRUE;
466 			IFLAGMOD(Iflag_only, -1, 1); /* '-i' exists */
467 			break;
468 
469 		case 'm':		/* streams msg report */
470 			Mflag = B_TRUE;
471 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
472 			break;
473 
474 		case 'n':		/* numeric format */
475 			Nflag = B_TRUE;
476 			break;
477 
478 		case 'r':		/* route tables */
479 			Rflag = B_TRUE;
480 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
481 			break;
482 
483 		case 'R':		/* security attributes */
484 			RSECflag = B_TRUE;
485 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
486 			break;
487 
488 		case 's':		/* per-protocol statistics */
489 			Sflag = B_TRUE;
490 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
491 			break;
492 
493 		case 'p':		/* arp/ndp table */
494 			Pflag = B_TRUE;
495 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
496 			break;
497 
498 		case 'M':		/* multicast routing tables */
499 			MMflag = B_TRUE;
500 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
501 			break;
502 
503 		case 'g':		/* multicast group membership */
504 			Gflag = B_TRUE;
505 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
506 			break;
507 
508 		case 'v':		/* verbose output format */
509 			Vflag = B_TRUE;
510 			IFLAGMOD(Iflag_only, 1, 0); /* see macro def'n */
511 			break;
512 
513 		case 'u':		/* show pid and uid information */
514 			Uflag = B_TRUE;
515 			break;
516 
517 		case 'x':		/* turn on debugging */
518 			Xflag = B_TRUE;
519 			break;
520 
521 		case 'f':
522 			process_filter(optarg);
523 			break;
524 
525 		case 'P':
526 			if (strcmp(optarg, "ip") == 0) {
527 				proto = IPPROTO_IP;
528 			} else if (strcmp(optarg, "ipv6") == 0 ||
529 			    strcmp(optarg, "ip6") == 0) {
530 				v4compat = 0;	/* Overridden */
531 				proto = IPPROTO_IPV6;
532 			} else if (strcmp(optarg, "icmp") == 0) {
533 				proto = IPPROTO_ICMP;
534 			} else if (strcmp(optarg, "icmpv6") == 0 ||
535 			    strcmp(optarg, "icmp6") == 0) {
536 				v4compat = 0;	/* Overridden */
537 				proto = IPPROTO_ICMPV6;
538 			} else if (strcmp(optarg, "igmp") == 0) {
539 				proto = IPPROTO_IGMP;
540 			} else if (strcmp(optarg, "udp") == 0) {
541 				proto = IPPROTO_UDP;
542 			} else if (strcmp(optarg, "tcp") == 0) {
543 				proto = IPPROTO_TCP;
544 			} else if (strcmp(optarg, "sctp") == 0) {
545 				proto = IPPROTO_SCTP;
546 			} else if (strcmp(optarg, "raw") == 0 ||
547 			    strcmp(optarg, "rawip") == 0) {
548 				proto = IPPROTO_RAW;
549 			} else {
550 				fatal(1, "%s: unknown protocol.\n", optarg);
551 			}
552 			break;
553 
554 		case 'I':
555 			ifname = optarg;
556 			Iflag = B_TRUE;
557 			IFLAGMOD(Iflag_only, -1, 1); /* see macro def'n */
558 			break;
559 
560 		case 'D':
561 			DHCPflag = B_TRUE;
562 			Iflag_only = 0;
563 			break;
564 
565 		case 'T':
566 			if (optarg) {
567 				if (*optarg == 'u')
568 					timestamp_fmt = UDATE;
569 				else if (*optarg == 'd')
570 					timestamp_fmt = DDATE;
571 				else
572 					usage(name);
573 			} else {
574 				usage(name);
575 			}
576 			break;
577 
578 		case '?':
579 		default:
580 			usage(name);
581 		}
582 	}
583 
584 	/*
585 	 * Make sure -R option is set only on a labeled system.
586 	 */
587 	if (RSECflag && !is_system_labeled()) {
588 		(void) fprintf(stderr, "-R set but labeling is not enabled\n");
589 		usage(name);
590 	}
591 
592 	/*
593 	 * Handle other arguments: find interval, count; the
594 	 * flags that accept 'interval' and 'count' are OR'd
595 	 * in the outermost 'if'; more flags may be added as
596 	 * required
597 	 */
598 	if (Iflag || Sflag || Mflag) {
599 		for (d = optind; d < argc; d++) {
600 			if (isnum(argv[d])) {
601 				interval = atoi(argv[d]);
602 				if (d + 1 < argc &&
603 				    isnum(argv[d + 1])) {
604 					count = atoi(argv[d + 1]);
605 					optind++;
606 				}
607 				optind++;
608 				if (interval == 0 || count == 0)
609 					usage(name);
610 				break;
611 			}
612 		}
613 	}
614 	if (optind < argc) {
615 		if (Iflag && isnum(argv[optind])) {
616 			count = atoi(argv[optind]);
617 			if (count == 0)
618 				usage(name);
619 			optind++;
620 		}
621 	}
622 	if (optind < argc) {
623 		(void) fprintf(stderr, "%s: extra arguments\n", name);
624 		usage(name);
625 	}
626 	if (interval)
627 		setbuf(stdout, NULL);
628 
629 	/*
630 	 * Start up the thread to check for name services warnings.
631 	 */
632 	if (thr_create(NULL, 0, ns_warning_thr, NULL,
633 	    THR_DETACHED | THR_DAEMON, NULL) != 0) {
634 		fatal(1, "%s: failed to create name services "
635 		    "thread: %s\n", name, strerror(errno));
636 	}
637 
638 	if (DHCPflag) {
639 		dhcp_report(Iflag ? ifname : NULL);
640 		exit(0);
641 	}
642 
643 	if (Uflag)
644 		process_hash_build();
645 
646 	/*
647 	 * Get this process's security label if the -R switch is set.
648 	 * We use this label as the current zone's security label.
649 	 */
650 	if (RSECflag) {
651 		zone_security_label = m_label_alloc(MAC_LABEL);
652 		if (zone_security_label == NULL)
653 			fatal(errno, "m_label_alloc() failed");
654 		if (getplabel(zone_security_label) < 0)
655 			fatal(errno, "getplabel() failed");
656 	}
657 
658 	/* Get data structures: priming before iteration */
659 	if (family_selected(AF_INET) || family_selected(AF_INET6)) {
660 		sd = mibopen();
661 		if (sd == -1)
662 			fatal(1, "can't open mib stream\n");
663 		if ((item = mibget(sd)) == NULL) {
664 			(void) close(sd);
665 			fatal(1, "mibget() failed\n");
666 		}
667 		/* Extract constant sizes - need do once only */
668 		mib_get_constants(item);
669 	}
670 	if ((kc = kstat_open()) == NULL) {
671 		mibfree(item);
672 		(void) close(sd);
673 		fail(1, "kstat_open(): can't open /dev/kstat");
674 	}
675 
676 	if (interval <= 0) {
677 		count = 1;
678 		once_only = B_TRUE;
679 	}
680 	for (;;) {
681 		mib_item_t *curritem = NULL; /* only for -[M]s */
682 
683 		if (timestamp_fmt != NODATE)
684 			print_timestamp(timestamp_fmt);
685 
686 		/* netstat: AF_INET[6] behaviour */
687 		if (family_selected(AF_INET) || family_selected(AF_INET6)) {
688 			if (Sflag) {
689 				curritem = mib_item_diff(previtem, item);
690 				if (curritem == NULL)
691 					fatal(1, "can't process mib data, "
692 					    "out of memory\n");
693 				mib_item_destroy(&previtem);
694 			}
695 
696 			if (!(Dflag || Iflag || Rflag || Sflag || Mflag ||
697 			    MMflag || Pflag || Gflag || DHCPflag)) {
698 				if (protocol_selected(IPPROTO_UDP))
699 					udp_report(item);
700 				if (protocol_selected(IPPROTO_TCP))
701 					tcp_report(item);
702 				if (protocol_selected(IPPROTO_SCTP))
703 					sctp_report(item);
704 			}
705 			if (Iflag)
706 				if_report(item, ifname, Iflag_only, once_only);
707 			if (Mflag)
708 				m_report();
709 			if (Rflag)
710 				ire_report(item);
711 			if (Sflag && MMflag) {
712 				mrt_stat_report(curritem);
713 			} else {
714 				if (Sflag)
715 					stat_report(curritem);
716 				if (MMflag)
717 					mrt_report(item);
718 			}
719 			if (Gflag)
720 				group_report(item);
721 			if (Pflag) {
722 				if (family_selected(AF_INET))
723 					arp_report(item);
724 				if (family_selected(AF_INET6))
725 					ndp_report(item);
726 			}
727 			if (Dflag)
728 				dce_report(item);
729 			mib_item_destroy(&curritem);
730 		}
731 
732 		/* netstat: AF_UNIX behaviour */
733 		if (family_selected(AF_UNIX) &&
734 		    (!(Dflag || Iflag || Rflag || Sflag || Mflag ||
735 		    MMflag || Pflag || Gflag)))
736 			uds_report(kc);
737 		(void) kstat_close(kc);
738 
739 		/* iteration handling code */
740 		if (count > 0 && --count == 0)
741 			break;
742 		(void) sleep(interval);
743 
744 		/* re-populating of data structures */
745 		if (family_selected(AF_INET) || family_selected(AF_INET6)) {
746 			if (Sflag) {
747 				/* previtem is a cut-down list */
748 				previtem = mib_item_dup(item);
749 				if (previtem == NULL)
750 					fatal(1, "can't process mib data, "
751 					    "out of memory\n");
752 			}
753 			mibfree(item);
754 			(void) close(sd);
755 			if ((sd = mibopen()) == -1)
756 				fatal(1, "can't open mib stream anymore\n");
757 			if ((item = mibget(sd)) == NULL) {
758 				(void) close(sd);
759 				fatal(1, "mibget() failed\n");
760 			}
761 		}
762 		if ((kc = kstat_open()) == NULL)
763 			fail(1, "kstat_open(): can't open /dev/kstat");
764 
765 	}
766 	mibfree(item);
767 	(void) close(sd);
768 	if (zone_security_label != NULL)
769 		m_label_free(zone_security_label);
770 
771 	if (Uflag)
772 		process_hash_free();
773 
774 	return (0);
775 }
776 
777 static int
778 isnum(char *p)
779 {
780 	int	len;
781 	int	i;
782 
783 	len = strlen(p);
784 	for (i = 0; i < len; i++)
785 		if (!isdigit(p[i]))
786 			return (0);
787 	return (1);
788 }
789 
790 /*
791  * ------------------------------ Process Hash -----------------------------
792  *
793  * When passed the -u option, netstat presents additional information against
794  * each socket showing the associated process ID(s), user(s) and command(s).
795  *
796  * The kernel provides some additional information for each socket, namely:
797  *   - inode;
798  *   - address family;
799  *   - socket type;
800  *   - major number;
801  *   - flags.
802  *
803  * Netstat must correlate this information against processes running on the
804  * system and the files which they have open.
805  *
806  * It does this by traversing /proc and checking each process' open files,
807  * looking for BSD sockets or file descriptors relating to TLI/XTI sockets.
808  * When it finds one, it retrieves information and records it in the
809  * 'process_table' hash table with the entry hashed by its inode.
810  *
811  * For a BSD socket, libproc is used to grab the process and retrieve
812  * further information. This is not necessary for TLI/XTI sockets since the
813  * information can be derived directly via stat().
814  *
815  * Note that each socket can be associated with more than one process.
816  */
817 
818 /*
819  * The size of the hash table for recording sockets found under /proc.
820  * This should be a prime number. The value below was chosen after testing
821  * on a busy web server to reduce the number of hash table collisions to
822  * fewer than five per slot.
823  */
824 #define	PROC_HASH_SIZE		2003
825 /* Maximum length of a username - anything larger will be truncated */
826 #define	PROC_USERNAME_SIZE	128
827 /* Maximum length of the string representation of a process ID */
828 #define	PROC_PID_SIZE		15
829 
830 #define	PROC_HASH(k) ((k) % PROC_HASH_SIZE)
831 
832 typedef struct proc_fdinfo {
833 	uint64_t ph_inode;
834 	uint64_t ph_fd;
835 	mode_t ph_mode;
836 	major_t ph_major;
837 	int ph_family;
838 	int ph_type;
839 
840 	char ph_fname[PRFNSZ];
841 	char ph_psargs[PRARGSZ];
842 	char ph_username[PROC_USERNAME_SIZE];
843 	pid_t ph_pid;
844 	char ph_pidstr[PROC_PID_SIZE];
845 
846 	struct proc_fdinfo *ph_next; /* Next (for collisions) */
847 	struct proc_fdinfo *ph_next_proc; /* Next process with this inode */
848 } proc_fdinfo_t;
849 
850 static proc_fdinfo_t *process_table[PROC_HASH_SIZE];
851 
852 static proc_fdinfo_t unknown_proc = {
853 	.ph_pid = 0,
854 	.ph_pidstr = "",
855 	.ph_username = "",
856 	.ph_fname = "",
857 	.ph_psargs = "",
858 	.ph_next_proc = NULL
859 };
860 
861 /*
862  * Gets username given uid. It doesn't return NULL.
863  */
864 static char *
865 get_username(uid_t u)
866 {
867 	static uid_t saved_uid = UID_MAX;
868 	static char saved_username[PROC_USERNAME_SIZE];
869 	struct passwd *pw = NULL;
870 
871 	if (u == UID_MAX)
872 		return ("<unknown>");
873 
874 	if (u == saved_uid && saved_username[0] != '\0')
875 		return (saved_username);
876 
877 	setpwent();
878 
879 	if ((pw = getpwuid(u)) != NULL) {
880 		(void) strlcpy(saved_username, pw->pw_name,
881 		    sizeof (saved_username));
882 	} else {
883 		(void) snprintf(saved_username, sizeof (saved_username),
884 		    "(%u)", u);
885 	}
886 
887 	saved_uid = u;
888 	return (saved_username);
889 }
890 
891 static proc_fdinfo_t *
892 process_hash_find(const mib2_socketInfoEntry_t *sie, int type, int family)
893 {
894 	proc_fdinfo_t *ph;
895 	uint_t idx = PROC_HASH(sie->sie_inode);
896 
897 	for (ph = process_table[idx]; ph != NULL; ph = ph->ph_next) {
898 		if (ph->ph_inode != sie->sie_inode)
899 			continue;
900 		if ((sie->sie_flags & MIB2_SOCKINFO_STREAM)) {
901 			/* TLI/XTI socket */
902 			if (S_ISCHR(ph->ph_mode) &&
903 			    major(sie->sie_dev) == ph->ph_major) {
904 				return (ph);
905 			}
906 		} else {
907 			if (S_ISSOCK(ph->ph_mode) && ph->ph_type == type &&
908 			    ph->ph_family == family) {
909 				return (ph);
910 			}
911 		}
912 	}
913 
914 	return (NULL);
915 }
916 
917 static proc_fdinfo_t *
918 process_hash_get(const mib2_socketInfoEntry_t *sie, int type, int family)
919 {
920 	proc_fdinfo_t *ph;
921 
922 	if (sie != NULL && sie->sie_inode > 0 &&
923 	    (ph = process_hash_find(sie, type, family)) != NULL) {
924 		return (ph);
925 	}
926 
927 	return (&unknown_proc);
928 }
929 
930 static void
931 process_hash_insert(proc_fdinfo_t *ph)
932 {
933 	uint_t idx = PROC_HASH(ph->ph_inode);
934 	proc_fdinfo_t *slotp;
935 
936 	mib2_socketInfoEntry_t sie = {
937 		.sie_inode = ph->ph_inode,
938 		.sie_dev = makedev(ph->ph_major, 0),
939 		.sie_flags = S_ISCHR(ph->ph_mode) ? MIB2_SOCKINFO_STREAM : 0
940 	};
941 
942 	slotp = process_hash_find(&sie, ph->ph_type, ph->ph_family);
943 
944 	if (slotp == NULL) {
945 		ph->ph_next = process_table[idx];
946 		process_table[idx] = ph;
947 	} else {
948 		ph->ph_next_proc = slotp->ph_next_proc;
949 		slotp->ph_next_proc = ph;
950 	}
951 }
952 
953 static void
954 process_hash_dump(void)
955 {
956 	unsigned int i;
957 
958 	(void) printf("--- Process hash table\n");
959 	for (i = 0; i < PROC_HASH_SIZE; i++) {
960 		proc_fdinfo_t *ph;
961 
962 		if (process_table[i] == NULL)
963 			continue;
964 
965 		(void) printf("Slot %d\n", i);
966 
967 		for (ph = process_table[i]; ph != NULL; ph = ph->ph_next) {
968 			proc_fdinfo_t *ph2;
969 
970 			(void) printf("    -> Inode %" PRIu64 "\n",
971 			    ph->ph_inode);
972 
973 			for (ph2 = ph; ph2 != NULL; ph2 = ph2->ph_next_proc) {
974 				(void) printf("        -> "
975 				    "/proc/%ld/fd/%" PRIu64 " %s - "
976 				    "fname %s - "
977 				    "psargs %s - "
978 				    "major %" PRIx32 " - "
979 				    "type/fam %d/%d\n",
980 				    ph2->ph_pid, ph2->ph_fd,
981 				    S_ISCHR(ph2->ph_mode) ? "CHR" : "SOCK",
982 				    ph2->ph_fname, ph2->ph_psargs,
983 				    ph2->ph_major,
984 				    ph2->ph_type, ph2->ph_family);
985 			}
986 		}
987 	}
988 }
989 
990 static int
991 process_hash_iterfd(const prfdinfo_t *pr, void *psinfop)
992 {
993 	psinfo_t *psinfo = psinfop;
994 	proc_fdinfo_t *ph;
995 
996 	/*
997 	 * We are interested both in sockets and in descriptors linked to
998 	 * network STREAMS character devices.
999 	 */
1000 	if (S_ISCHR(pr->pr_mode)) {
1001 		/*
1002 		 * There's no elegant way to determine if a character device
1003 		 * supports TLI, so just check a hardcoded list of known TLI
1004 		 * devices.
1005 		 */
1006 		const char *tlidevs[] = {
1007 		    "tcp", "tcp6", "udp", "udp6", NULL
1008 		};
1009 		boolean_t istli = B_FALSE;
1010 		const char *path;
1011 		char *dev;
1012 		int i;
1013 
1014 		path = proc_fdinfo_misc(pr, PR_PATHNAME, NULL);
1015 		if (path == NULL)
1016 			return (0);
1017 
1018 		/* global zone: /devices paths */
1019 		dev = strrchr(path, ':');
1020 		/* also check the /dev path for zones */
1021 		if (dev == NULL)
1022 			dev = strrchr(path, '/');
1023 		if (dev == NULL)
1024 			return (0);
1025 		dev++; /* skip past the `:' or '/' */
1026 
1027 		for (i = 0; tlidevs[i] != NULL; i++) {
1028 			if (strcmp(dev, tlidevs[i]) == 0) {
1029 				istli = B_TRUE;
1030 				break;
1031 			}
1032 		}
1033 		if (!istli)
1034 			return (0);
1035 	} else if (!S_ISSOCK(pr->pr_mode)) {
1036 		return (0);
1037 	}
1038 
1039 	if ((ph = calloc(1, sizeof (proc_fdinfo_t))) == NULL)
1040 		fatal(1, "out of memory\n");
1041 
1042 	ph->ph_pid = psinfo->pr_pid;
1043 	if (ph->ph_pid > 0)
1044 		(void) snprintf(ph->ph_pidstr, PROC_PID_SIZE, "%" PRIu64,
1045 		    ph->ph_pid);
1046 	ph->ph_inode = pr->pr_ino;
1047 	ph->ph_fd = pr->pr_fd;
1048 	ph->ph_major = pr->pr_rmajor;
1049 	ph->ph_mode = pr->pr_mode;
1050 	(void) strlcpy(ph->ph_fname, psinfo->pr_fname, sizeof (ph->ph_fname));
1051 	(void) strlcpy(ph->ph_psargs, psinfo->pr_psargs,
1052 	    sizeof (ph->ph_psargs));
1053 	(void) strlcpy(ph->ph_username, get_username(psinfo->pr_uid),
1054 	    sizeof (ph->ph_username));
1055 
1056 	if (S_ISSOCK(pr->pr_mode)) {
1057 		const struct sockaddr *sa;
1058 		const int *type;
1059 
1060 		/* Determine the socket type */
1061 		type = proc_fdinfo_misc(pr, PR_SOCKOPT_TYPE, NULL);
1062 		if (type != NULL)
1063 			ph->ph_type = *type;
1064 
1065 		/* Determine the protocol family */
1066 		sa = proc_fdinfo_misc(pr, PR_SOCKETNAME, NULL);
1067 		if (sa != NULL)
1068 			ph->ph_family = sa->sa_family;
1069 	}
1070 
1071 	process_hash_insert(ph);
1072 
1073 	return (0);
1074 }
1075 
1076 static int
1077 process_hash_iterproc(psinfo_t *psinfo, lwpsinfo_t *lwp __unused,
1078     void *arg __unused)
1079 {
1080 	static pid_t me = -1;
1081 
1082 	if (me == -1)
1083 		me = getpid();
1084 
1085 	if (psinfo->pr_pid == me)
1086 		return (0);
1087 
1088 	/*
1089 	 * We do not use libproc's Pfdinfo_iter() here as it requires
1090 	 * grabbing the process.
1091 	 */
1092 	return (proc_fdwalk(psinfo->pr_pid, process_hash_iterfd, psinfo));
1093 }
1094 
1095 static void
1096 process_hash_build(void)
1097 {
1098 	(void) proc_walk(process_hash_iterproc, NULL, PR_WALK_PROC);
1099 
1100 	if (Xflag)
1101 		process_hash_dump();
1102 }
1103 
1104 static void
1105 process_hash_free(void)
1106 {
1107 	unsigned int i;
1108 
1109 	for (i = 0; i < PROC_HASH_SIZE; i++) {
1110 		proc_fdinfo_t *ph, *ph_next;
1111 
1112 		for (ph = process_table[i]; ph != NULL; ph = ph_next) {
1113 			ph_next = ph->ph_next;
1114 			free(ph);
1115 		}
1116 		process_table[i] = NULL;
1117 	}
1118 }
1119 
1120 /* --------------------------------- MIBGET -------------------------------- */
1121 
1122 static mib_item_t *
1123 mibget(int sd)
1124 {
1125 	/*
1126 	 * buf is an automatic for this function, so the
1127 	 * compiler has complete control over its alignment;
1128 	 * it is assumed this alignment is satisfactory for
1129 	 * it to be casted to certain other struct pointers
1130 	 * here, such as struct T_optmgmt_ack * .
1131 	 */
1132 	uintptr_t		buf[512 / sizeof (uintptr_t)];
1133 	int			flags;
1134 	int			i, j, getcode;
1135 	struct strbuf		ctlbuf, databuf;
1136 	struct T_optmgmt_req	*tor = (struct T_optmgmt_req *)buf;
1137 	struct T_optmgmt_ack	*toa = (struct T_optmgmt_ack *)buf;
1138 	struct T_error_ack	*tea = (struct T_error_ack *)buf;
1139 	struct opthdr		*req;
1140 	mib_item_t		*first_item = NULL;
1141 	mib_item_t		*last_item  = NULL;
1142 	mib_item_t		*temp;
1143 
1144 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
1145 	tor->OPT_offset = sizeof (struct T_optmgmt_req);
1146 	tor->OPT_length = sizeof (struct opthdr);
1147 	tor->MGMT_flags = T_CURRENT;
1148 
1149 	/*
1150 	 * Note: we use the special level value below so that IP will return
1151 	 * us information concerning IRE_MARK_TESTHIDDEN routes.
1152 	 */
1153 	req = (struct opthdr *)&tor[1];
1154 	req->level = EXPER_IP_AND_ALL_IRES;
1155 	req->name  = 0;
1156 	req->len   = 1;
1157 
1158 	ctlbuf.buf = (char *)buf;
1159 	ctlbuf.len = tor->OPT_length + tor->OPT_offset;
1160 	flags = 0;
1161 	if (putmsg(sd, &ctlbuf, (struct strbuf *)0, flags) == -1) {
1162 		perror("mibget: putmsg(ctl) failed");
1163 		goto error_exit;
1164 	}
1165 
1166 	/*
1167 	 * Each reply consists of a ctl part for one fixed structure
1168 	 * or table, as defined in mib2.h.  The format is a T_OPTMGMT_ACK,
1169 	 * containing an opthdr structure.  level/name identify the entry,
1170 	 * len is the size of the data part of the message.
1171 	 */
1172 	req = (struct opthdr *)&toa[1];
1173 	ctlbuf.maxlen = sizeof (buf);
1174 	j = 1;
1175 	for (;;) {
1176 		flags = 0;
1177 		getcode = getmsg(sd, &ctlbuf, (struct strbuf *)0, &flags);
1178 		if (getcode == -1) {
1179 			perror("mibget getmsg(ctl) failed");
1180 			if (Xflag) {
1181 				(void) fputs("#   level   name    len\n",
1182 				    stderr);
1183 				i = 0;
1184 				for (last_item = first_item; last_item;
1185 				    last_item = last_item->next_item)
1186 					(void) printf("%d  %4d   %5d   %d\n",
1187 					    ++i,
1188 					    last_item->group,
1189 					    last_item->mib_id,
1190 					    last_item->length);
1191 			}
1192 			goto error_exit;
1193 		}
1194 		if (getcode == 0 &&
1195 		    ctlbuf.len >= sizeof (struct T_optmgmt_ack) &&
1196 		    toa->PRIM_type == T_OPTMGMT_ACK &&
1197 		    toa->MGMT_flags == T_SUCCESS &&
1198 		    req->len == 0) {
1199 			if (Xflag)
1200 				(void) printf("mibget getmsg() %d returned "
1201 				    "EOD (level %ld, name %ld)\n",
1202 				    j, req->level, req->name);
1203 			return (first_item);		/* this is EOD msg */
1204 		}
1205 
1206 		if (ctlbuf.len >= sizeof (struct T_error_ack) &&
1207 		    tea->PRIM_type == T_ERROR_ACK) {
1208 			(void) fprintf(stderr,
1209 			    "mibget %d gives T_ERROR_ACK: TLI_error = 0x%lx, "
1210 			    "UNIX_error = 0x%lx\n",
1211 			    j, tea->TLI_error, tea->UNIX_error);
1212 
1213 			errno = (tea->TLI_error == TSYSERR) ?
1214 			    tea->UNIX_error : EPROTO;
1215 			goto error_exit;
1216 		}
1217 
1218 		if (getcode != MOREDATA ||
1219 		    ctlbuf.len < sizeof (struct T_optmgmt_ack) ||
1220 		    toa->PRIM_type != T_OPTMGMT_ACK ||
1221 		    toa->MGMT_flags != T_SUCCESS) {
1222 			(void) printf("mibget getmsg(ctl) %d returned %d, "
1223 			    "ctlbuf.len = %d, PRIM_type = %ld\n",
1224 			    j, getcode, ctlbuf.len, toa->PRIM_type);
1225 
1226 			if (toa->PRIM_type == T_OPTMGMT_ACK)
1227 				(void) printf("T_OPTMGMT_ACK: "
1228 				    "MGMT_flags = 0x%lx, req->len = %ld\n",
1229 				    toa->MGMT_flags, req->len);
1230 			errno = ENOMSG;
1231 			goto error_exit;
1232 		}
1233 
1234 		temp = (mib_item_t *)malloc(sizeof (mib_item_t));
1235 		if (temp == NULL) {
1236 			perror("mibget malloc failed");
1237 			goto error_exit;
1238 		}
1239 		if (last_item != NULL)
1240 			last_item->next_item = temp;
1241 		else
1242 			first_item = temp;
1243 		last_item = temp;
1244 		last_item->next_item = NULL;
1245 		last_item->group = req->level;
1246 		last_item->mib_id = req->name;
1247 		last_item->length = req->len;
1248 		last_item->valp = malloc((int)req->len);
1249 		if (last_item->valp == NULL)
1250 			goto error_exit;
1251 		if (Xflag)
1252 			(void) printf("msg %4d: group = %-4d mib_id = %-5d "
1253 			    "length = %d\n",
1254 			    j, last_item->group, last_item->mib_id,
1255 			    last_item->length);
1256 
1257 		databuf.maxlen = last_item->length;
1258 		databuf.buf    = (char *)last_item->valp;
1259 		databuf.len    = 0;
1260 		flags = 0;
1261 		getcode = getmsg(sd, (struct strbuf *)0, &databuf, &flags);
1262 		if (getcode == -1) {
1263 			perror("mibget getmsg(data) failed");
1264 			goto error_exit;
1265 		} else if (getcode != 0) {
1266 			(void) printf("mibget getmsg(data) returned %d, "
1267 			    "databuf.maxlen = %d, databuf.len = %d\n",
1268 			    getcode, databuf.maxlen, databuf.len);
1269 			goto error_exit;
1270 		}
1271 		j++;
1272 	}
1273 	/* NOTREACHED */
1274 
1275 error_exit:;
1276 	mibfree(first_item);
1277 	return (NULL);
1278 }
1279 
1280 /*
1281  * mibfree: frees a linked list of type (mib_item_t *)
1282  * returned by mibget(); this is NOT THE SAME AS
1283  * mib_item_destroy(), so should be used for objects
1284  * returned by mibget() only
1285  */
1286 static void
1287 mibfree(mib_item_t *firstitem)
1288 {
1289 	mib_item_t *lastitem;
1290 
1291 	while (firstitem != NULL) {
1292 		lastitem = firstitem;
1293 		firstitem = firstitem->next_item;
1294 		if (lastitem->valp != NULL)
1295 			free(lastitem->valp);
1296 		free(lastitem);
1297 	}
1298 }
1299 
1300 static int
1301 mibopen(void)
1302 {
1303 	int	sd;
1304 
1305 	sd = open("/dev/arp", O_RDWR);
1306 	if (sd == -1) {
1307 		perror("arp open");
1308 		return (-1);
1309 	}
1310 	if (ioctl(sd, I_PUSH, "tcp") == -1) {
1311 		perror("tcp I_PUSH");
1312 		(void) close(sd);
1313 		return (-1);
1314 	}
1315 	if (ioctl(sd, I_PUSH, "udp") == -1) {
1316 		perror("udp I_PUSH");
1317 		(void) close(sd);
1318 		return (-1);
1319 	}
1320 	if (ioctl(sd, I_PUSH, "icmp") == -1) {
1321 		perror("icmp I_PUSH");
1322 		(void) close(sd);
1323 		return (-1);
1324 	}
1325 	return (sd);
1326 }
1327 
1328 /*
1329  * mib_item_dup: returns a clean mib_item_t * linked
1330  * list, so that for every element item->mib_id is 0;
1331  * to deallocate this linked list, use mib_item_destroy
1332  */
1333 static mib_item_t *
1334 mib_item_dup(mib_item_t *item)
1335 {
1336 	int	c = 0;
1337 	mib_item_t *localp;
1338 	mib_item_t *tempp;
1339 
1340 	for (tempp = item; tempp; tempp = tempp->next_item)
1341 		if (tempp->mib_id == 0)
1342 			c++;
1343 	tempp = NULL;
1344 
1345 	localp = (mib_item_t *)malloc(c * sizeof (mib_item_t));
1346 	if (localp == NULL)
1347 		return (NULL);
1348 	c = 0;
1349 	for (; item; item = item->next_item) {
1350 		if (item->mib_id == 0) {
1351 			/* Replicate item in localp */
1352 			(localp[c]).next_item = NULL;
1353 			(localp[c]).group = item->group;
1354 			(localp[c]).mib_id = item->mib_id;
1355 			(localp[c]).length = item->length;
1356 			(localp[c]).valp = (uintptr_t *)malloc(
1357 			    item->length);
1358 			if ((localp[c]).valp == NULL) {
1359 				mib_item_destroy(&localp);
1360 				return (NULL);
1361 			}
1362 			(void *) memcpy((localp[c]).valp,
1363 			    item->valp,
1364 			    item->length);
1365 			tempp = &(localp[c]);
1366 			if (c > 0)
1367 				(localp[c - 1]).next_item = tempp;
1368 			c++;
1369 		}
1370 	}
1371 	return (localp);
1372 }
1373 
1374 /*
1375  * mib_item_diff: takes two (mib_item_t *) linked lists
1376  * item1 and item2 and computes the difference between
1377  * differentiable values in item2 against item1 for every
1378  * given member of item2; returns an mib_item_t * linked
1379  * list of diff's, or a copy of item2 if item1 is NULL;
1380  * will return NULL if system out of memory; works only
1381  * for item->mib_id == 0
1382  */
1383 static mib_item_t *
1384 mib_item_diff(mib_item_t *item1, mib_item_t *item2)
1385 {
1386 	int	nitems	= 0; /* no. of items in item2 */
1387 	mib_item_t *tempp2;  /* walking copy of item2 */
1388 	mib_item_t *tempp1;  /* walking copy of item1 */
1389 	mib_item_t *diffp;
1390 	mib_item_t *diffptr; /* walking copy of diffp */
1391 	mib_item_t *prevp = NULL;
1392 
1393 	if (item1 == NULL) {
1394 		diffp = mib_item_dup(item2);
1395 		return (diffp);
1396 	}
1397 
1398 	for (tempp2 = item2;
1399 	    tempp2;
1400 	    tempp2 = tempp2->next_item) {
1401 		if (tempp2->mib_id == 0)
1402 			switch (tempp2->group) {
1403 			/*
1404 			 * upon adding a case here, the same
1405 			 * must also be added in the next
1406 			 * switch statement, alongwith
1407 			 * appropriate code
1408 			 */
1409 			case MIB2_IP:
1410 			case MIB2_IP6:
1411 			case EXPER_DVMRP:
1412 			case EXPER_IGMP:
1413 			case MIB2_ICMP:
1414 			case MIB2_ICMP6:
1415 			case MIB2_TCP:
1416 			case MIB2_UDP:
1417 			case MIB2_SCTP:
1418 			case EXPER_RAWIP:
1419 				nitems++;
1420 			}
1421 	}
1422 	tempp2 = NULL;
1423 	if (nitems == 0) {
1424 		diffp = mib_item_dup(item2);
1425 		return (diffp);
1426 	}
1427 
1428 	diffp = calloc(nitems, sizeof (mib_item_t));
1429 	if (diffp == NULL)
1430 		return (NULL);
1431 	diffptr = diffp;
1432 	for (tempp2 = item2; tempp2 != NULL; tempp2 = tempp2->next_item) {
1433 		if (tempp2->mib_id != 0)
1434 			continue;
1435 		for (tempp1 = item1; tempp1 != NULL;
1436 		    tempp1 = tempp1->next_item) {
1437 			if (!(tempp1->mib_id == 0 &&
1438 			    tempp1->group == tempp2->group &&
1439 			    tempp1->mib_id == tempp2->mib_id))
1440 				continue;
1441 			/* found comparable data sets */
1442 			if (prevp != NULL)
1443 				prevp->next_item = diffptr;
1444 			switch (tempp2->group) {
1445 			/*
1446 			 * Indenting note: Because of long variable names
1447 			 * in cases MIB2_IP6 and MIB2_ICMP6, their contents
1448 			 * have been indented by one tab space only
1449 			 */
1450 			case MIB2_IP: {
1451 				mib2_ip_t *i2 = (mib2_ip_t *)tempp2->valp;
1452 				mib2_ip_t *i1 = (mib2_ip_t *)tempp1->valp;
1453 				mib2_ip_t *d;
1454 
1455 				diffptr->group = tempp2->group;
1456 				diffptr->mib_id = tempp2->mib_id;
1457 				diffptr->length = tempp2->length;
1458 				d = calloc(1, tempp2->length);
1459 				if (d == NULL)
1460 					goto mibdiff_out_of_memory;
1461 				diffptr->valp = d;
1462 				d->ipForwarding = i2->ipForwarding;
1463 				d->ipDefaultTTL = i2->ipDefaultTTL;
1464 				MDIFF(d, i2, i1, ipInReceives);
1465 				MDIFF(d, i2, i1, ipInHdrErrors);
1466 				MDIFF(d, i2, i1, ipInAddrErrors);
1467 				MDIFF(d, i2, i1, ipInCksumErrs);
1468 				MDIFF(d, i2, i1, ipForwDatagrams);
1469 				MDIFF(d, i2, i1, ipForwProhibits);
1470 				MDIFF(d, i2, i1, ipInUnknownProtos);
1471 				MDIFF(d, i2, i1, ipInDiscards);
1472 				MDIFF(d, i2, i1, ipInDelivers);
1473 				MDIFF(d, i2, i1, ipOutRequests);
1474 				MDIFF(d, i2, i1, ipOutDiscards);
1475 				MDIFF(d, i2, i1, ipOutNoRoutes);
1476 				MDIFF(d, i2, i1, ipReasmTimeout);
1477 				MDIFF(d, i2, i1, ipReasmReqds);
1478 				MDIFF(d, i2, i1, ipReasmOKs);
1479 				MDIFF(d, i2, i1, ipReasmFails);
1480 				MDIFF(d, i2, i1, ipReasmDuplicates);
1481 				MDIFF(d, i2, i1, ipReasmPartDups);
1482 				MDIFF(d, i2, i1, ipFragOKs);
1483 				MDIFF(d, i2, i1, ipFragFails);
1484 				MDIFF(d, i2, i1, ipFragCreates);
1485 				MDIFF(d, i2, i1, ipRoutingDiscards);
1486 				MDIFF(d, i2, i1, tcpInErrs);
1487 				MDIFF(d, i2, i1, udpNoPorts);
1488 				MDIFF(d, i2, i1, udpInCksumErrs);
1489 				MDIFF(d, i2, i1, udpInOverflows);
1490 				MDIFF(d, i2, i1, rawipInOverflows);
1491 				MDIFF(d, i2, i1, ipsecInSucceeded);
1492 				MDIFF(d, i2, i1, ipsecInFailed);
1493 				MDIFF(d, i2, i1, ipInIPv6);
1494 				MDIFF(d, i2, i1, ipOutIPv6);
1495 				MDIFF(d, i2, i1, ipOutSwitchIPv6);
1496 				prevp = diffptr++;
1497 				break;
1498 			}
1499 			case MIB2_IP6: {
1500 			mib2_ipv6IfStatsEntry_t *i2;
1501 			mib2_ipv6IfStatsEntry_t *i1;
1502 			mib2_ipv6IfStatsEntry_t *d;
1503 
1504 			i2 = (mib2_ipv6IfStatsEntry_t *)tempp2->valp;
1505 			i1 = (mib2_ipv6IfStatsEntry_t *)tempp1->valp;
1506 			diffptr->group = tempp2->group;
1507 			diffptr->mib_id = tempp2->mib_id;
1508 			diffptr->length = tempp2->length;
1509 			d = calloc(1, tempp2->length);
1510 			if (d == NULL)
1511 				goto mibdiff_out_of_memory;
1512 			diffptr->valp = d;
1513 			d->ipv6Forwarding = i2->ipv6Forwarding;
1514 			d->ipv6DefaultHopLimit =
1515 			    i2->ipv6DefaultHopLimit;
1516 
1517 			MDIFF(d, i2, i1, ipv6InReceives);
1518 			MDIFF(d, i2, i1, ipv6InHdrErrors);
1519 			MDIFF(d, i2, i1, ipv6InTooBigErrors);
1520 			MDIFF(d, i2, i1, ipv6InNoRoutes);
1521 			MDIFF(d, i2, i1, ipv6InAddrErrors);
1522 			MDIFF(d, i2, i1, ipv6InUnknownProtos);
1523 			MDIFF(d, i2, i1, ipv6InTruncatedPkts);
1524 			MDIFF(d, i2, i1, ipv6InDiscards);
1525 			MDIFF(d, i2, i1, ipv6InDelivers);
1526 			MDIFF(d, i2, i1, ipv6OutForwDatagrams);
1527 			MDIFF(d, i2, i1, ipv6OutRequests);
1528 			MDIFF(d, i2, i1, ipv6OutDiscards);
1529 			MDIFF(d, i2, i1, ipv6OutNoRoutes);
1530 			MDIFF(d, i2, i1, ipv6OutFragOKs);
1531 			MDIFF(d, i2, i1, ipv6OutFragFails);
1532 			MDIFF(d, i2, i1, ipv6OutFragCreates);
1533 			MDIFF(d, i2, i1, ipv6ReasmReqds);
1534 			MDIFF(d, i2, i1, ipv6ReasmOKs);
1535 			MDIFF(d, i2, i1, ipv6ReasmFails);
1536 			MDIFF(d, i2, i1, ipv6InMcastPkts);
1537 			MDIFF(d, i2, i1, ipv6OutMcastPkts);
1538 			MDIFF(d, i2, i1, ipv6ReasmDuplicates);
1539 			MDIFF(d, i2, i1, ipv6ReasmPartDups);
1540 			MDIFF(d, i2, i1, ipv6ForwProhibits);
1541 			MDIFF(d, i2, i1, udpInCksumErrs);
1542 			MDIFF(d, i2, i1, udpInOverflows);
1543 			MDIFF(d, i2, i1, rawipInOverflows);
1544 			MDIFF(d, i2, i1, ipv6InIPv4);
1545 			MDIFF(d, i2, i1, ipv6OutIPv4);
1546 			MDIFF(d, i2, i1, ipv6OutSwitchIPv4);
1547 			prevp = diffptr++;
1548 			break;
1549 			}
1550 			case EXPER_DVMRP: {
1551 				struct mrtstat *m2;
1552 				struct mrtstat *m1;
1553 				struct mrtstat *d;
1554 
1555 				m2 = (struct mrtstat *)tempp2->valp;
1556 				m1 = (struct mrtstat *)tempp1->valp;
1557 				diffptr->group = tempp2->group;
1558 				diffptr->mib_id = tempp2->mib_id;
1559 				diffptr->length = tempp2->length;
1560 				d = calloc(1, tempp2->length);
1561 				if (d == NULL)
1562 					goto mibdiff_out_of_memory;
1563 				diffptr->valp = d;
1564 				MDIFF(d, m2, m1, mrts_mfc_hits);
1565 				MDIFF(d, m2, m1, mrts_mfc_misses);
1566 				MDIFF(d, m2, m1, mrts_fwd_in);
1567 				MDIFF(d, m2, m1, mrts_fwd_out);
1568 				d->mrts_upcalls = m2->mrts_upcalls;
1569 				MDIFF(d, m2, m1, mrts_fwd_drop);
1570 				MDIFF(d, m2, m1, mrts_bad_tunnel);
1571 				MDIFF(d, m2, m1, mrts_cant_tunnel);
1572 				MDIFF(d, m2, m1, mrts_wrong_if);
1573 				MDIFF(d, m2, m1, mrts_upq_ovflw);
1574 				MDIFF(d, m2, m1, mrts_cache_cleanups);
1575 				MDIFF(d, m2, m1, mrts_drop_sel);
1576 				MDIFF(d, m2, m1, mrts_q_overflow);
1577 				MDIFF(d, m2, m1, mrts_pkt2large);
1578 				MDIFF(d, m2, m1, mrts_pim_badversion);
1579 				MDIFF(d, m2, m1, mrts_pim_rcv_badcsum);
1580 				MDIFF(d, m2, m1, mrts_pim_badregisters);
1581 				MDIFF(d, m2, m1, mrts_pim_regforwards);
1582 				MDIFF(d, m2, m1, mrts_pim_regsend_drops);
1583 				MDIFF(d, m2, m1, mrts_pim_malformed);
1584 				MDIFF(d, m2, m1, mrts_pim_nomemory);
1585 				prevp = diffptr++;
1586 				break;
1587 			}
1588 			case EXPER_IGMP: {
1589 				struct igmpstat *i2;
1590 				struct igmpstat *i1;
1591 				struct igmpstat *d;
1592 
1593 				i2 = (struct igmpstat *)tempp2->valp;
1594 				i1 = (struct igmpstat *)tempp1->valp;
1595 				diffptr->group = tempp2->group;
1596 				diffptr->mib_id = tempp2->mib_id;
1597 				diffptr->length = tempp2->length;
1598 				d = calloc(1, tempp2->length);
1599 				if (d == NULL)
1600 					goto mibdiff_out_of_memory;
1601 				diffptr->valp = d;
1602 				MDIFF(d, i2, i1, igps_rcv_total);
1603 				MDIFF(d, i2, i1, igps_rcv_tooshort);
1604 				MDIFF(d, i2, i1, igps_rcv_badsum);
1605 				MDIFF(d, i2, i1, igps_rcv_queries);
1606 				MDIFF(d, i2, i1, igps_rcv_badqueries);
1607 				MDIFF(d, i2, i1, igps_rcv_reports);
1608 				MDIFF(d, i2, i1, igps_rcv_badreports);
1609 				MDIFF(d, i2, i1, igps_rcv_ourreports);
1610 				MDIFF(d, i2, i1, igps_snd_reports);
1611 				prevp = diffptr++;
1612 				break;
1613 			}
1614 			case MIB2_ICMP: {
1615 				mib2_icmp_t *i2;
1616 				mib2_icmp_t *i1;
1617 				mib2_icmp_t *d;
1618 
1619 				i2 = (mib2_icmp_t *)tempp2->valp;
1620 				i1 = (mib2_icmp_t *)tempp1->valp;
1621 				diffptr->group = tempp2->group;
1622 				diffptr->mib_id = tempp2->mib_id;
1623 				diffptr->length = tempp2->length;
1624 				d = calloc(1, tempp2->length);
1625 				if (d == NULL)
1626 					goto mibdiff_out_of_memory;
1627 				diffptr->valp = d;
1628 				MDIFF(d, i2, i1, icmpInMsgs);
1629 				MDIFF(d, i2, i1, icmpInErrors);
1630 				MDIFF(d, i2, i1, icmpInCksumErrs);
1631 				MDIFF(d, i2, i1, icmpInUnknowns);
1632 				MDIFF(d, i2, i1, icmpInDestUnreachs);
1633 				MDIFF(d, i2, i1, icmpInTimeExcds);
1634 				MDIFF(d, i2, i1, icmpInParmProbs);
1635 				MDIFF(d, i2, i1, icmpInSrcQuenchs);
1636 				MDIFF(d, i2, i1, icmpInRedirects);
1637 				MDIFF(d, i2, i1, icmpInBadRedirects);
1638 				MDIFF(d, i2, i1, icmpInEchos);
1639 				MDIFF(d, i2, i1, icmpInEchoReps);
1640 				MDIFF(d, i2, i1, icmpInTimestamps);
1641 				MDIFF(d, i2, i1, icmpInAddrMasks);
1642 				MDIFF(d, i2, i1, icmpInAddrMaskReps);
1643 				MDIFF(d, i2, i1, icmpInFragNeeded);
1644 				MDIFF(d, i2, i1, icmpOutMsgs);
1645 				MDIFF(d, i2, i1, icmpOutDrops);
1646 				MDIFF(d, i2, i1, icmpOutErrors);
1647 				MDIFF(d, i2, i1, icmpOutDestUnreachs);
1648 				MDIFF(d, i2, i1, icmpOutTimeExcds);
1649 				MDIFF(d, i2, i1, icmpOutParmProbs);
1650 				MDIFF(d, i2, i1, icmpOutSrcQuenchs);
1651 				MDIFF(d, i2, i1, icmpOutRedirects);
1652 				MDIFF(d, i2, i1, icmpOutEchos);
1653 				MDIFF(d, i2, i1, icmpOutEchoReps);
1654 				MDIFF(d, i2, i1, icmpOutTimestamps);
1655 				MDIFF(d, i2, i1, icmpOutTimestampReps);
1656 				MDIFF(d, i2, i1, icmpOutAddrMasks);
1657 				MDIFF(d, i2, i1, icmpOutAddrMaskReps);
1658 				MDIFF(d, i2, i1, icmpOutFragNeeded);
1659 				MDIFF(d, i2, i1, icmpInOverflows);
1660 				prevp = diffptr++;
1661 				break;
1662 			}
1663 			case MIB2_ICMP6: {
1664 	mib2_ipv6IfIcmpEntry_t *i2;
1665 	mib2_ipv6IfIcmpEntry_t *i1;
1666 	mib2_ipv6IfIcmpEntry_t *d;
1667 
1668 	i2 = (mib2_ipv6IfIcmpEntry_t *)tempp2->valp;
1669 	i1 = (mib2_ipv6IfIcmpEntry_t *)tempp1->valp;
1670 	diffptr->group = tempp2->group;
1671 	diffptr->mib_id = tempp2->mib_id;
1672 	diffptr->length = tempp2->length;
1673 	d = calloc(1, tempp2->length);
1674 	if (d == NULL)
1675 		goto mibdiff_out_of_memory;
1676 	diffptr->valp = d;
1677 	MDIFF(d, i2, i1, ipv6IfIcmpInMsgs);
1678 	MDIFF(d, i2, i1, ipv6IfIcmpInErrors);
1679 	MDIFF(d, i2, i1, ipv6IfIcmpInDestUnreachs);
1680 	MDIFF(d, i2, i1, ipv6IfIcmpInAdminProhibs);
1681 	MDIFF(d, i2, i1, ipv6IfIcmpInTimeExcds);
1682 	MDIFF(d, i2, i1, ipv6IfIcmpInParmProblems);
1683 	MDIFF(d, i2, i1, ipv6IfIcmpInPktTooBigs);
1684 	MDIFF(d, i2, i1, ipv6IfIcmpInEchos);
1685 	MDIFF(d, i2, i1, ipv6IfIcmpInEchoReplies);
1686 	MDIFF(d, i2, i1, ipv6IfIcmpInRouterSolicits);
1687 	MDIFF(d, i2, i1, ipv6IfIcmpInRouterAdvertisements);
1688 	MDIFF(d, i2, i1, ipv6IfIcmpInNeighborSolicits);
1689 	MDIFF(d, i2, i1, ipv6IfIcmpInNeighborAdvertisements);
1690 	MDIFF(d, i2, i1, ipv6IfIcmpInRedirects);
1691 	MDIFF(d, i2, i1, ipv6IfIcmpInBadRedirects);
1692 	MDIFF(d, i2, i1, ipv6IfIcmpInGroupMembQueries);
1693 	MDIFF(d, i2, i1, ipv6IfIcmpInGroupMembResponses);
1694 	MDIFF(d, i2, i1, ipv6IfIcmpInGroupMembReductions);
1695 	MDIFF(d, i2, i1, ipv6IfIcmpInOverflows);
1696 	MDIFF(d, i2, i1, ipv6IfIcmpOutMsgs);
1697 	MDIFF(d, i2, i1, ipv6IfIcmpOutErrors);
1698 	MDIFF(d, i2, i1, ipv6IfIcmpOutDestUnreachs);
1699 	MDIFF(d, i2, i1, ipv6IfIcmpOutAdminProhibs);
1700 	MDIFF(d, i2, i1, ipv6IfIcmpOutTimeExcds);
1701 	MDIFF(d, i2, i1, ipv6IfIcmpOutParmProblems);
1702 	MDIFF(d, i2, i1, ipv6IfIcmpOutPktTooBigs);
1703 	MDIFF(d, i2, i1, ipv6IfIcmpOutEchos);
1704 	MDIFF(d, i2, i1, ipv6IfIcmpOutEchoReplies);
1705 	MDIFF(d, i2, i1, ipv6IfIcmpOutRouterSolicits);
1706 	MDIFF(d, i2, i1, ipv6IfIcmpOutRouterAdvertisements);
1707 	MDIFF(d, i2, i1, ipv6IfIcmpOutNeighborSolicits);
1708 	MDIFF(d, i2, i1, ipv6IfIcmpOutNeighborAdvertisements);
1709 	MDIFF(d, i2, i1, ipv6IfIcmpOutRedirects);
1710 	MDIFF(d, i2, i1, ipv6IfIcmpOutGroupMembQueries);
1711 	MDIFF(d, i2, i1, ipv6IfIcmpOutGroupMembResponses);
1712 	MDIFF(d, i2, i1, ipv6IfIcmpOutGroupMembReductions);
1713 	prevp = diffptr++;
1714 	break;
1715 			}
1716 			case MIB2_TCP: {
1717 				mib2_tcp_t *t2;
1718 				mib2_tcp_t *t1;
1719 				mib2_tcp_t *d;
1720 
1721 				t2 = (mib2_tcp_t *)tempp2->valp;
1722 				t1 = (mib2_tcp_t *)tempp1->valp;
1723 				diffptr->group = tempp2->group;
1724 				diffptr->mib_id = tempp2->mib_id;
1725 				diffptr->length = tempp2->length;
1726 				d = calloc(1, tempp2->length);
1727 				if (d == NULL)
1728 					goto mibdiff_out_of_memory;
1729 				diffptr->valp = d;
1730 				d->tcpRtoMin = t2->tcpRtoMin;
1731 				d->tcpRtoMax = t2->tcpRtoMax;
1732 				d->tcpMaxConn = t2->tcpMaxConn;
1733 				MDIFF(d, t2, t1, tcpActiveOpens);
1734 				MDIFF(d, t2, t1, tcpPassiveOpens);
1735 				MDIFF(d, t2, t1, tcpAttemptFails);
1736 				MDIFF(d, t2, t1, tcpEstabResets);
1737 				d->tcpCurrEstab = t2->tcpCurrEstab;
1738 				MDIFF(d, t2, t1, tcpHCOutSegs);
1739 				MDIFF(d, t2, t1, tcpOutDataSegs);
1740 				MDIFF(d, t2, t1, tcpOutDataBytes);
1741 				MDIFF(d, t2, t1, tcpRetransSegs);
1742 				MDIFF(d, t2, t1, tcpRetransBytes);
1743 				MDIFF(d, t2, t1, tcpOutAck);
1744 				MDIFF(d, t2, t1, tcpOutAckDelayed);
1745 				MDIFF(d, t2, t1, tcpOutUrg);
1746 				MDIFF(d, t2, t1, tcpOutWinUpdate);
1747 				MDIFF(d, t2, t1, tcpOutWinProbe);
1748 				MDIFF(d, t2, t1, tcpOutControl);
1749 				MDIFF(d, t2, t1, tcpOutRsts);
1750 				MDIFF(d, t2, t1, tcpOutFastRetrans);
1751 				MDIFF(d, t2, t1, tcpHCInSegs);
1752 				MDIFF(d, t2, t1, tcpInAckSegs);
1753 				MDIFF(d, t2, t1, tcpInAckBytes);
1754 				MDIFF(d, t2, t1, tcpInDupAck);
1755 				MDIFF(d, t2, t1, tcpInAckUnsent);
1756 				MDIFF(d, t2, t1, tcpInDataInorderSegs);
1757 				MDIFF(d, t2, t1, tcpInDataInorderBytes);
1758 				MDIFF(d, t2, t1, tcpInDataUnorderSegs);
1759 				MDIFF(d, t2, t1, tcpInDataUnorderBytes);
1760 				MDIFF(d, t2, t1, tcpInDataDupSegs);
1761 				MDIFF(d, t2, t1, tcpInDataDupBytes);
1762 				MDIFF(d, t2, t1, tcpInDataPartDupSegs);
1763 				MDIFF(d, t2, t1, tcpInDataPartDupBytes);
1764 				MDIFF(d, t2, t1, tcpInDataPastWinSegs);
1765 				MDIFF(d, t2, t1, tcpInDataPastWinBytes);
1766 				MDIFF(d, t2, t1, tcpInWinProbe);
1767 				MDIFF(d, t2, t1, tcpInWinUpdate);
1768 				MDIFF(d, t2, t1, tcpInClosed);
1769 				MDIFF(d, t2, t1, tcpRttNoUpdate);
1770 				MDIFF(d, t2, t1, tcpRttUpdate);
1771 				MDIFF(d, t2, t1, tcpTimRetrans);
1772 				MDIFF(d, t2, t1, tcpTimRetransDrop);
1773 				MDIFF(d, t2, t1, tcpTimKeepalive);
1774 				MDIFF(d, t2, t1, tcpTimKeepaliveProbe);
1775 				MDIFF(d, t2, t1, tcpTimKeepaliveDrop);
1776 				MDIFF(d, t2, t1, tcpListenDrop);
1777 				MDIFF(d, t2, t1, tcpListenDropQ0);
1778 				MDIFF(d, t2, t1, tcpHalfOpenDrop);
1779 				MDIFF(d, t2, t1, tcpOutSackRetransSegs);
1780 				prevp = diffptr++;
1781 				break;
1782 			}
1783 			case MIB2_UDP: {
1784 				mib2_udp_t *u2;
1785 				mib2_udp_t *u1;
1786 				mib2_udp_t *d;
1787 
1788 				u2 = (mib2_udp_t *)tempp2->valp;
1789 				u1 = (mib2_udp_t *)tempp1->valp;
1790 				diffptr->group = tempp2->group;
1791 				diffptr->mib_id = tempp2->mib_id;
1792 				diffptr->length = tempp2->length;
1793 				d = calloc(1, tempp2->length);
1794 				if (d == NULL)
1795 					goto mibdiff_out_of_memory;
1796 				diffptr->valp = d;
1797 				MDIFF(d, u2, u1, udpHCInDatagrams);
1798 				MDIFF(d, u2, u1, udpInErrors);
1799 				MDIFF(d, u2, u1, udpHCOutDatagrams);
1800 				MDIFF(d, u2, u1, udpOutErrors);
1801 				prevp = diffptr++;
1802 				break;
1803 			}
1804 			case MIB2_SCTP: {
1805 				mib2_sctp_t *s2;
1806 				mib2_sctp_t *s1;
1807 				mib2_sctp_t *d;
1808 
1809 				s2 = (mib2_sctp_t *)tempp2->valp;
1810 				s1 = (mib2_sctp_t *)tempp1->valp;
1811 				diffptr->group = tempp2->group;
1812 				diffptr->mib_id = tempp2->mib_id;
1813 				diffptr->length = tempp2->length;
1814 				d = calloc(1, tempp2->length);
1815 				if (d == NULL)
1816 					goto mibdiff_out_of_memory;
1817 				diffptr->valp = d;
1818 				d->sctpRtoAlgorithm = s2->sctpRtoAlgorithm;
1819 				d->sctpRtoMin = s2->sctpRtoMin;
1820 				d->sctpRtoMax = s2->sctpRtoMax;
1821 				d->sctpRtoInitial = s2->sctpRtoInitial;
1822 				d->sctpMaxAssocs = s2->sctpMaxAssocs;
1823 				d->sctpValCookieLife = s2->sctpValCookieLife;
1824 				d->sctpMaxInitRetr = s2->sctpMaxInitRetr;
1825 				d->sctpCurrEstab = s2->sctpCurrEstab;
1826 				MDIFF(d, s2, s1, sctpActiveEstab);
1827 				MDIFF(d, s2, s1, sctpPassiveEstab);
1828 				MDIFF(d, s2, s1, sctpAborted);
1829 				MDIFF(d, s2, s1, sctpShutdowns);
1830 				MDIFF(d, s2, s1, sctpOutOfBlue);
1831 				MDIFF(d, s2, s1, sctpChecksumError);
1832 				MDIFF(d, s2, s1, sctpOutCtrlChunks);
1833 				MDIFF(d, s2, s1, sctpOutOrderChunks);
1834 				MDIFF(d, s2, s1, sctpOutUnorderChunks);
1835 				MDIFF(d, s2, s1, sctpRetransChunks);
1836 				MDIFF(d, s2, s1, sctpOutAck);
1837 				MDIFF(d, s2, s1, sctpOutAckDelayed);
1838 				MDIFF(d, s2, s1, sctpOutWinUpdate);
1839 				MDIFF(d, s2, s1, sctpOutFastRetrans);
1840 				MDIFF(d, s2, s1, sctpOutWinProbe);
1841 				MDIFF(d, s2, s1, sctpInCtrlChunks);
1842 				MDIFF(d, s2, s1, sctpInOrderChunks);
1843 				MDIFF(d, s2, s1, sctpInUnorderChunks);
1844 				MDIFF(d, s2, s1, sctpInAck);
1845 				MDIFF(d, s2, s1, sctpInDupAck);
1846 				MDIFF(d, s2, s1, sctpInAckUnsent);
1847 				MDIFF(d, s2, s1, sctpFragUsrMsgs);
1848 				MDIFF(d, s2, s1, sctpReasmUsrMsgs);
1849 				MDIFF(d, s2, s1, sctpOutSCTPPkts);
1850 				MDIFF(d, s2, s1, sctpInSCTPPkts);
1851 				MDIFF(d, s2, s1, sctpInInvalidCookie);
1852 				MDIFF(d, s2, s1, sctpTimRetrans);
1853 				MDIFF(d, s2, s1, sctpTimRetransDrop);
1854 				MDIFF(d, s2, s1, sctpTimHeartBeatProbe);
1855 				MDIFF(d, s2, s1, sctpTimHeartBeatDrop);
1856 				MDIFF(d, s2, s1, sctpListenDrop);
1857 				MDIFF(d, s2, s1, sctpInClosed);
1858 				prevp = diffptr++;
1859 				break;
1860 			}
1861 			case EXPER_RAWIP: {
1862 				mib2_rawip_t *r2;
1863 				mib2_rawip_t *r1;
1864 				mib2_rawip_t *d;
1865 
1866 				r2 = (mib2_rawip_t *)tempp2->valp;
1867 				r1 = (mib2_rawip_t *)tempp1->valp;
1868 				diffptr->group = tempp2->group;
1869 				diffptr->mib_id = tempp2->mib_id;
1870 				diffptr->length = tempp2->length;
1871 				d = calloc(1, tempp2->length);
1872 				if (d == NULL)
1873 					goto mibdiff_out_of_memory;
1874 				diffptr->valp = d;
1875 				MDIFF(d, r2, r1, rawipInDatagrams);
1876 				MDIFF(d, r2, r1, rawipInErrors);
1877 				MDIFF(d, r2, r1, rawipInCksumErrs);
1878 				MDIFF(d, r2, r1, rawipOutDatagrams);
1879 				MDIFF(d, r2, r1, rawipOutErrors);
1880 				prevp = diffptr++;
1881 				break;
1882 			}
1883 			/*
1884 			 * there are more "group" types but they aren't
1885 			 * required for the -s and -Ms options
1886 			 */
1887 			}
1888 		}
1889 		tempp1 = NULL;
1890 	}
1891 	tempp2 = NULL;
1892 	diffptr--;
1893 	diffptr->next_item = NULL;
1894 	return (diffp);
1895 
1896 mibdiff_out_of_memory:;
1897 	mib_item_destroy(&diffp);
1898 	return (NULL);
1899 }
1900 
1901 /*
1902  * mib_item_destroy: cleans up a mib_item_t *
1903  * that was created by calling mib_item_dup or
1904  * mib_item_diff
1905  */
1906 static void
1907 mib_item_destroy(mib_item_t **itemp)
1908 {
1909 	int	nitems = 0;
1910 	int	c = 0;
1911 	mib_item_t *tempp;
1912 
1913 	if (itemp == NULL || *itemp == NULL)
1914 		return;
1915 
1916 	for (tempp = *itemp; tempp != NULL; tempp = tempp->next_item)
1917 		if (tempp->mib_id == 0)
1918 			nitems++;
1919 		else
1920 			return;	/* cannot destroy! */
1921 
1922 	if (nitems == 0)
1923 		return;		/* cannot destroy! */
1924 
1925 	for (c = nitems - 1; c >= 0; c--) {
1926 		if ((itemp[0][c]).valp != NULL)
1927 			free((itemp[0][c]).valp);
1928 	}
1929 	free(*itemp);
1930 
1931 	*itemp = NULL;
1932 }
1933 
1934 /* Compare two Octet_ts.  Return B_TRUE if they match, B_FALSE if not. */
1935 static boolean_t
1936 octetstrmatch(const Octet_t *a, const Octet_t *b)
1937 {
1938 	if (a == NULL || b == NULL)
1939 		return (B_FALSE);
1940 
1941 	if (a->o_length != b->o_length)
1942 		return (B_FALSE);
1943 
1944 	return (memcmp(a->o_bytes, b->o_bytes, a->o_length) == 0);
1945 }
1946 
1947 /* If octetstr() changes make an appropriate change to STR_EXPAND */
1948 static char *
1949 octetstr(const Octet_t *op, int code, char *dst, uint_t dstlen)
1950 {
1951 	int	i;
1952 	char	*cp;
1953 
1954 	cp = dst;
1955 	if (op) {
1956 		for (i = 0; i < op->o_length; i++) {
1957 			switch (code) {
1958 			case 'd':
1959 				if (cp - dst + 4 > dstlen) {
1960 					*cp = '\0';
1961 					return (dst);
1962 				}
1963 				(void) snprintf(cp, 5, "%d.",
1964 				    0xff & op->o_bytes[i]);
1965 				cp = strchr(cp, '\0');
1966 				break;
1967 			case 'a':
1968 				if (cp - dst + 1 > dstlen) {
1969 					*cp = '\0';
1970 					return (dst);
1971 				}
1972 				*cp++ = op->o_bytes[i];
1973 				break;
1974 			case 'h':
1975 			default:
1976 				if (cp - dst + 3 > dstlen) {
1977 					*cp = '\0';
1978 					return (dst);
1979 				}
1980 				(void) snprintf(cp, 4, "%02x:",
1981 				    0xff & op->o_bytes[i]);
1982 				cp += 3;
1983 				break;
1984 			}
1985 		}
1986 	}
1987 	if (code != 'a' && cp != dst)
1988 		cp--;
1989 	*cp = '\0';
1990 	return (dst);
1991 }
1992 
1993 static const char *
1994 mitcp_state(int state, const mib2_transportMLPEntry_t *attr)
1995 {
1996 	static char tcpsbuf[50];
1997 	const char *cp;
1998 
1999 	switch (state) {
2000 	case TCPS_CLOSED:
2001 		cp = "CLOSED";
2002 		break;
2003 	case TCPS_IDLE:
2004 		cp = "IDLE";
2005 		break;
2006 	case TCPS_BOUND:
2007 		cp = "BOUND";
2008 		break;
2009 	case TCPS_LISTEN:
2010 		cp = "LISTEN";
2011 		break;
2012 	case TCPS_SYN_SENT:
2013 		cp = "SYN_SENT";
2014 		break;
2015 	case TCPS_SYN_RCVD:
2016 		cp = "SYN_RCVD";
2017 		break;
2018 	case TCPS_ESTABLISHED:
2019 		cp = "ESTABLISHED";
2020 		break;
2021 	case TCPS_CLOSE_WAIT:
2022 		cp = "CLOSE_WAIT";
2023 		break;
2024 	case TCPS_FIN_WAIT_1:
2025 		cp = "FIN_WAIT_1";
2026 		break;
2027 	case TCPS_CLOSING:
2028 		cp = "CLOSING";
2029 		break;
2030 	case TCPS_LAST_ACK:
2031 		cp = "LAST_ACK";
2032 		break;
2033 	case TCPS_FIN_WAIT_2:
2034 		cp = "FIN_WAIT_2";
2035 		break;
2036 	case TCPS_TIME_WAIT:
2037 		cp = "TIME_WAIT";
2038 		break;
2039 	default:
2040 		(void) snprintf(tcpsbuf, sizeof (tcpsbuf),
2041 		    "UnknownState(%d)", state);
2042 		cp = tcpsbuf;
2043 		break;
2044 	}
2045 
2046 	if (RSECflag && attr != NULL && attr->tme_flags != 0) {
2047 		if (cp != tcpsbuf) {
2048 			(void) strlcpy(tcpsbuf, cp, sizeof (tcpsbuf));
2049 			cp = tcpsbuf;
2050 		}
2051 		if (attr->tme_flags & MIB2_TMEF_PRIVATE)
2052 			(void) strlcat(tcpsbuf, " P", sizeof (tcpsbuf));
2053 		if (attr->tme_flags & MIB2_TMEF_SHARED)
2054 			(void) strlcat(tcpsbuf, " S", sizeof (tcpsbuf));
2055 	}
2056 
2057 	return (cp);
2058 }
2059 
2060 static const char *
2061 miudp_state(int state, const mib2_transportMLPEntry_t *attr)
2062 {
2063 	static char udpsbuf[50];
2064 	const char *cp;
2065 
2066 	switch (state) {
2067 	case MIB2_UDP_unbound:
2068 		cp = "Unbound";
2069 		break;
2070 	case MIB2_UDP_idle:
2071 		cp = "Idle";
2072 		break;
2073 	case MIB2_UDP_connected:
2074 		cp = "Connected";
2075 		break;
2076 	default:
2077 		(void) snprintf(udpsbuf, sizeof (udpsbuf),
2078 		    "Unknown State(%d)", state);
2079 		cp = udpsbuf;
2080 		break;
2081 	}
2082 
2083 	if (RSECflag && attr != NULL && attr->tme_flags != 0) {
2084 		if (cp != udpsbuf) {
2085 			(void) strlcpy(udpsbuf, cp, sizeof (udpsbuf));
2086 			cp = udpsbuf;
2087 		}
2088 		if (attr->tme_flags & MIB2_TMEF_PRIVATE)
2089 			(void) strlcat(udpsbuf, " P", sizeof (udpsbuf));
2090 		if (attr->tme_flags & MIB2_TMEF_SHARED)
2091 			(void) strlcat(udpsbuf, " S", sizeof (udpsbuf));
2092 	}
2093 
2094 	return (cp);
2095 }
2096 
2097 static int odd;
2098 
2099 static void
2100 prval_init(void)
2101 {
2102 	odd = 0;
2103 }
2104 
2105 static void
2106 prval(char *str, Counter val)
2107 {
2108 	(void) printf("\t%-20s=%6u", str, val);
2109 	if (odd++ & 1)
2110 		(void) putchar('\n');
2111 }
2112 
2113 static void
2114 prval64(char *str, Counter64 val)
2115 {
2116 	(void) printf("\t%-20s=%6llu", str, val);
2117 	if (odd++ & 1)
2118 		(void) putchar('\n');
2119 }
2120 
2121 static void
2122 pr_int_val(char *str, int val)
2123 {
2124 	(void) printf("\t%-20s=%6d", str, val);
2125 	if (odd++ & 1)
2126 		(void) putchar('\n');
2127 }
2128 
2129 static void
2130 pr_sctp_rtoalgo(char *str, int val)
2131 {
2132 	(void) printf("\t%-20s=", str);
2133 	switch (val) {
2134 		case MIB2_SCTP_RTOALGO_OTHER:
2135 			(void) printf("%6.6s", "other");
2136 			break;
2137 
2138 		case MIB2_SCTP_RTOALGO_VANJ:
2139 			(void) printf("%6.6s", "vanj");
2140 			break;
2141 
2142 		default:
2143 			(void) printf("%6d", val);
2144 			break;
2145 	}
2146 	if (odd++ & 1)
2147 		(void) putchar('\n');
2148 }
2149 
2150 static void
2151 prval_end(void)
2152 {
2153 	if (odd++ & 1)
2154 		(void) putchar('\n');
2155 }
2156 
2157 /* Extract constant sizes */
2158 static void
2159 mib_get_constants(mib_item_t *item)
2160 {
2161 	for (; item; item = item->next_item) {
2162 		if (item->mib_id != 0)
2163 			continue;
2164 
2165 		switch (item->group) {
2166 		case MIB2_IP: {
2167 			mib2_ip_t	*ip = (mib2_ip_t *)item->valp;
2168 
2169 			ipAddrEntrySize = ip->ipAddrEntrySize;
2170 			ipRouteEntrySize = ip->ipRouteEntrySize;
2171 			ipNetToMediaEntrySize = ip->ipNetToMediaEntrySize;
2172 			ipMemberEntrySize = ip->ipMemberEntrySize;
2173 			ipGroupSourceEntrySize = ip->ipGroupSourceEntrySize;
2174 			ipRouteAttributeSize = ip->ipRouteAttributeSize;
2175 			transportMLPSize = ip->transportMLPSize;
2176 			ipDestEntrySize = ip->ipDestEntrySize;
2177 			assert(IS_P2ALIGNED(ipAddrEntrySize,
2178 			    sizeof (mib2_ipAddrEntry_t *)));
2179 			assert(IS_P2ALIGNED(ipRouteEntrySize,
2180 			    sizeof (mib2_ipRouteEntry_t *)));
2181 			assert(IS_P2ALIGNED(ipNetToMediaEntrySize,
2182 			    sizeof (mib2_ipNetToMediaEntry_t *)));
2183 			assert(IS_P2ALIGNED(ipMemberEntrySize,
2184 			    sizeof (ip_member_t *)));
2185 			assert(IS_P2ALIGNED(ipGroupSourceEntrySize,
2186 			    sizeof (ip_grpsrc_t *)));
2187 			assert(IS_P2ALIGNED(ipRouteAttributeSize,
2188 			    sizeof (mib2_ipAttributeEntry_t *)));
2189 			assert(IS_P2ALIGNED(transportMLPSize,
2190 			    sizeof (mib2_transportMLPEntry_t *)));
2191 			break;
2192 		}
2193 		case EXPER_DVMRP: {
2194 			struct mrtstat	*mrts = (struct mrtstat *)item->valp;
2195 
2196 			vifctlSize = mrts->mrts_vifctlSize;
2197 			mfcctlSize = mrts->mrts_mfcctlSize;
2198 			assert(IS_P2ALIGNED(vifctlSize,
2199 			    sizeof (struct vifclt *)));
2200 			assert(IS_P2ALIGNED(mfcctlSize,
2201 			    sizeof (struct mfcctl *)));
2202 			break;
2203 		}
2204 		case MIB2_IP6: {
2205 			mib2_ipv6IfStatsEntry_t *ip6;
2206 			/* Just use the first entry */
2207 
2208 			ip6 = (mib2_ipv6IfStatsEntry_t *)item->valp;
2209 			ipv6IfStatsEntrySize = ip6->ipv6IfStatsEntrySize;
2210 			ipv6AddrEntrySize = ip6->ipv6AddrEntrySize;
2211 			ipv6RouteEntrySize = ip6->ipv6RouteEntrySize;
2212 			ipv6NetToMediaEntrySize = ip6->ipv6NetToMediaEntrySize;
2213 			ipv6MemberEntrySize = ip6->ipv6MemberEntrySize;
2214 			ipv6GroupSourceEntrySize =
2215 			    ip6->ipv6GroupSourceEntrySize;
2216 			assert(IS_P2ALIGNED(ipv6IfStatsEntrySize,
2217 			    sizeof (mib2_ipv6IfStatsEntry_t *)));
2218 			assert(IS_P2ALIGNED(ipv6AddrEntrySize,
2219 			    sizeof (mib2_ipv6AddrEntry_t *)));
2220 			assert(IS_P2ALIGNED(ipv6RouteEntrySize,
2221 			    sizeof (mib2_ipv6RouteEntry_t *)));
2222 			assert(IS_P2ALIGNED(ipv6NetToMediaEntrySize,
2223 			    sizeof (mib2_ipv6NetToMediaEntry_t *)));
2224 			assert(IS_P2ALIGNED(ipv6MemberEntrySize,
2225 			    sizeof (ipv6_member_t *)));
2226 			assert(IS_P2ALIGNED(ipv6GroupSourceEntrySize,
2227 			    sizeof (ipv6_grpsrc_t *)));
2228 			break;
2229 		}
2230 		case MIB2_ICMP6: {
2231 			mib2_ipv6IfIcmpEntry_t *icmp6;
2232 			/* Just use the first entry */
2233 
2234 			icmp6 = (mib2_ipv6IfIcmpEntry_t *)item->valp;
2235 			ipv6IfIcmpEntrySize = icmp6->ipv6IfIcmpEntrySize;
2236 			assert(IS_P2ALIGNED(ipv6IfIcmpEntrySize,
2237 			    sizeof (mib2_ipv6IfIcmpEntry_t *)));
2238 			break;
2239 		}
2240 		case MIB2_TCP: {
2241 			mib2_tcp_t	*tcp = (mib2_tcp_t *)item->valp;
2242 
2243 			tcpConnEntrySize = tcp->tcpConnTableSize;
2244 			tcp6ConnEntrySize = tcp->tcp6ConnTableSize;
2245 			assert(IS_P2ALIGNED(tcpConnEntrySize,
2246 			    sizeof (mib2_tcpConnEntry_t *)));
2247 			assert(IS_P2ALIGNED(tcp6ConnEntrySize,
2248 			    sizeof (mib2_tcp6ConnEntry_t *)));
2249 			break;
2250 		}
2251 		case MIB2_UDP: {
2252 			mib2_udp_t	*udp = (mib2_udp_t *)item->valp;
2253 
2254 			udpEntrySize = udp->udpEntrySize;
2255 			udp6EntrySize = udp->udp6EntrySize;
2256 			assert(IS_P2ALIGNED(udpEntrySize,
2257 			    sizeof (mib2_udpEntry_t *)));
2258 			assert(IS_P2ALIGNED(udp6EntrySize,
2259 			    sizeof (mib2_udp6Entry_t *)));
2260 			break;
2261 		}
2262 		case MIB2_SCTP: {
2263 			mib2_sctp_t	*sctp = (mib2_sctp_t *)item->valp;
2264 
2265 			sctpEntrySize = sctp->sctpEntrySize;
2266 			sctpLocalEntrySize = sctp->sctpLocalEntrySize;
2267 			sctpRemoteEntrySize = sctp->sctpRemoteEntrySize;
2268 			break;
2269 		}
2270 		}
2271 	}
2272 
2273 	if (Xflag) {
2274 		(void) puts("mib_get_constants:");
2275 		(void) printf("\tipv6IfStatsEntrySize %d\n",
2276 		    ipv6IfStatsEntrySize);
2277 		(void) printf("\tipAddrEntrySize %d\n", ipAddrEntrySize);
2278 		(void) printf("\tipRouteEntrySize %d\n", ipRouteEntrySize);
2279 		(void) printf("\tipNetToMediaEntrySize %d\n",
2280 		    ipNetToMediaEntrySize);
2281 		(void) printf("\tipMemberEntrySize %d\n", ipMemberEntrySize);
2282 		(void) printf("\tipRouteAttributeSize %d\n",
2283 		    ipRouteAttributeSize);
2284 		(void) printf("\tvifctlSize %d\n", vifctlSize);
2285 		(void) printf("\tmfcctlSize %d\n", mfcctlSize);
2286 
2287 		(void) printf("\tipv6AddrEntrySize %d\n", ipv6AddrEntrySize);
2288 		(void) printf("\tipv6RouteEntrySize %d\n", ipv6RouteEntrySize);
2289 		(void) printf("\tipv6NetToMediaEntrySize %d\n",
2290 		    ipv6NetToMediaEntrySize);
2291 		(void) printf("\tipv6MemberEntrySize %d\n",
2292 		    ipv6MemberEntrySize);
2293 		(void) printf("\tipv6IfIcmpEntrySize %d\n",
2294 		    ipv6IfIcmpEntrySize);
2295 		(void) printf("\tipDestEntrySize %d\n", ipDestEntrySize);
2296 		(void) printf("\ttransportMLPSize %d\n", transportMLPSize);
2297 		(void) printf("\ttcpConnEntrySize %d\n", tcpConnEntrySize);
2298 		(void) printf("\ttcp6ConnEntrySize %d\n", tcp6ConnEntrySize);
2299 		(void) printf("\tudpEntrySize %d\n", udpEntrySize);
2300 		(void) printf("\tudp6EntrySize %d\n", udp6EntrySize);
2301 		(void) printf("\tsctpEntrySize %d\n", sctpEntrySize);
2302 		(void) printf("\tsctpLocalEntrySize %d\n", sctpLocalEntrySize);
2303 		(void) printf("\tsctpRemoteEntrySize %d\n",
2304 		    sctpRemoteEntrySize);
2305 	}
2306 }
2307 
2308 /* ----------------------------- STAT_REPORT ------------------------------- */
2309 
2310 static void
2311 stat_report(mib_item_t *item)
2312 {
2313 	int	jtemp = 0;
2314 	char	ifname[LIFNAMSIZ + 1];
2315 
2316 	for (; item; item = item->next_item) {
2317 		if (Xflag) {
2318 			(void) printf("[%4d] Group = %d, mib_id = %d, "
2319 			    "length = %d, valp = 0x%p\n",
2320 			    jtemp++, item->group, item->mib_id,
2321 			    item->length, item->valp);
2322 		}
2323 		if (item->mib_id != 0)
2324 			continue;
2325 
2326 		switch (item->group) {
2327 		case MIB2_IP: {
2328 			mib2_ip_t	*ip = (mib2_ip_t *)item->valp;
2329 
2330 			if (protocol_selected(IPPROTO_IP) &&
2331 			    family_selected(AF_INET)) {
2332 				(void) fputs(v4compat ? "\nIP" : "\nIPv4",
2333 				    stdout);
2334 				print_ip_stats(ip);
2335 			}
2336 			break;
2337 		}
2338 		case MIB2_ICMP: {
2339 			mib2_icmp_t	*icmp =
2340 			    (mib2_icmp_t *)item->valp;
2341 
2342 			if (protocol_selected(IPPROTO_ICMP) &&
2343 			    family_selected(AF_INET)) {
2344 				(void) fputs(v4compat ? "\nICMP" : "\nICMPv4",
2345 				    stdout);
2346 				print_icmp_stats(icmp);
2347 			}
2348 			break;
2349 		}
2350 		case MIB2_IP6: {
2351 			mib2_ipv6IfStatsEntry_t *ip6;
2352 			mib2_ipv6IfStatsEntry_t sum6;
2353 
2354 			if (!(protocol_selected(IPPROTO_IPV6)) ||
2355 			    !(family_selected(AF_INET6)))
2356 				break;
2357 			bzero(&sum6, sizeof (sum6));
2358 			for (ip6 = (mib2_ipv6IfStatsEntry_t *)item->valp;
2359 			    (char *)ip6 < (char *)item->valp + item->length;
2360 			    ip6 = (mib2_ipv6IfStatsEntry_t *)((char *)ip6 +
2361 			    ipv6IfStatsEntrySize)) {
2362 				if (ip6->ipv6IfIndex == 0) {
2363 					/*
2364 					 * The "unknown interface" ip6
2365 					 * mib. Just add to the sum.
2366 					 */
2367 					sum_ip6_stats(ip6, &sum6);
2368 					continue;
2369 				}
2370 				if (Aflag) {
2371 					(void) printf("\nIPv6 for %s\n",
2372 					    ifindex2str(ip6->ipv6IfIndex,
2373 					    ifname));
2374 					print_ip6_stats(ip6);
2375 				}
2376 				sum_ip6_stats(ip6, &sum6);
2377 			}
2378 			(void) fputs("\nIPv6", stdout);
2379 			print_ip6_stats(&sum6);
2380 			break;
2381 		}
2382 		case MIB2_ICMP6: {
2383 			mib2_ipv6IfIcmpEntry_t *icmp6;
2384 			mib2_ipv6IfIcmpEntry_t sum6;
2385 
2386 			if (!(protocol_selected(IPPROTO_ICMPV6)) ||
2387 			    !(family_selected(AF_INET6)))
2388 				break;
2389 			bzero(&sum6, sizeof (sum6));
2390 			for (icmp6 = (mib2_ipv6IfIcmpEntry_t *)item->valp;
2391 			    (char *)icmp6 < (char *)item->valp + item->length;
2392 			    icmp6 = (void *)((char *)icmp6 +
2393 			    ipv6IfIcmpEntrySize)) {
2394 				if (icmp6->ipv6IfIcmpIfIndex == 0) {
2395 					/*
2396 					 * The "unknown interface" icmp6
2397 					 * mib. Just add to the sum.
2398 					 */
2399 					sum_icmp6_stats(icmp6, &sum6);
2400 					continue;
2401 				}
2402 				if (Aflag) {
2403 					(void) printf("\nICMPv6 for %s\n",
2404 					    ifindex2str(
2405 					    icmp6->ipv6IfIcmpIfIndex, ifname));
2406 					print_icmp6_stats(icmp6);
2407 				}
2408 				sum_icmp6_stats(icmp6, &sum6);
2409 			}
2410 			(void) fputs("\nICMPv6", stdout);
2411 			print_icmp6_stats(&sum6);
2412 			break;
2413 		}
2414 		case MIB2_TCP: {
2415 			mib2_tcp_t	*tcp = (mib2_tcp_t *)item->valp;
2416 
2417 			if (protocol_selected(IPPROTO_TCP) &&
2418 			    (family_selected(AF_INET) ||
2419 			    family_selected(AF_INET6))) {
2420 				(void) fputs("\nTCP", stdout);
2421 				print_tcp_stats(tcp);
2422 			}
2423 			break;
2424 		}
2425 		case MIB2_UDP: {
2426 			mib2_udp_t	*udp = (mib2_udp_t *)item->valp;
2427 
2428 			if (protocol_selected(IPPROTO_UDP) &&
2429 			    (family_selected(AF_INET) ||
2430 			    family_selected(AF_INET6))) {
2431 				(void) fputs("\nUDP", stdout);
2432 				print_udp_stats(udp);
2433 			}
2434 			break;
2435 		}
2436 		case MIB2_SCTP: {
2437 			mib2_sctp_t	*sctp = (mib2_sctp_t *)item->valp;
2438 
2439 			if (protocol_selected(IPPROTO_SCTP) &&
2440 			    (family_selected(AF_INET) ||
2441 			    family_selected(AF_INET6))) {
2442 				(void) fputs("\nSCTP", stdout);
2443 				print_sctp_stats(sctp);
2444 			}
2445 			break;
2446 		}
2447 		case EXPER_RAWIP: {
2448 			mib2_rawip_t	*rawip =
2449 			    (mib2_rawip_t *)item->valp;
2450 
2451 			if (protocol_selected(IPPROTO_RAW) &&
2452 			    (family_selected(AF_INET) ||
2453 			    family_selected(AF_INET6))) {
2454 				(void) fputs("\nRAWIP", stdout);
2455 				print_rawip_stats(rawip);
2456 			}
2457 			break;
2458 		}
2459 		case EXPER_IGMP: {
2460 			struct igmpstat	*igps =
2461 			    (struct igmpstat *)item->valp;
2462 
2463 			if (protocol_selected(IPPROTO_IGMP) &&
2464 			    (family_selected(AF_INET))) {
2465 				(void) fputs("\nIGMP:\n", stdout);
2466 				print_igmp_stats(igps);
2467 			}
2468 			break;
2469 		}
2470 		}
2471 	}
2472 	(void) putchar('\n');
2473 	(void) fflush(stdout);
2474 }
2475 
2476 static void
2477 print_ip_stats(mib2_ip_t *ip)
2478 {
2479 	prval_init();
2480 	pr_int_val("ipForwarding",	ip->ipForwarding);
2481 	pr_int_val("ipDefaultTTL",	ip->ipDefaultTTL);
2482 	prval("ipInReceives",		ip->ipInReceives);
2483 	prval("ipInHdrErrors",		ip->ipInHdrErrors);
2484 	prval("ipInAddrErrors",		ip->ipInAddrErrors);
2485 	prval("ipInCksumErrs",		ip->ipInCksumErrs);
2486 	prval("ipForwDatagrams",	ip->ipForwDatagrams);
2487 	prval("ipForwProhibits",	ip->ipForwProhibits);
2488 	prval("ipInUnknownProtos",	ip->ipInUnknownProtos);
2489 	prval("ipInDiscards",		ip->ipInDiscards);
2490 	prval("ipInDelivers",		ip->ipInDelivers);
2491 	prval("ipOutRequests",		ip->ipOutRequests);
2492 	prval("ipOutDiscards",		ip->ipOutDiscards);
2493 	prval("ipOutNoRoutes",		ip->ipOutNoRoutes);
2494 	pr_int_val("ipReasmTimeout",	ip->ipReasmTimeout);
2495 	prval("ipReasmReqds",		ip->ipReasmReqds);
2496 	prval("ipReasmOKs",		ip->ipReasmOKs);
2497 	prval("ipReasmFails",		ip->ipReasmFails);
2498 	prval("ipReasmDuplicates",	ip->ipReasmDuplicates);
2499 	prval("ipReasmPartDups",	ip->ipReasmPartDups);
2500 	prval("ipFragOKs",		ip->ipFragOKs);
2501 	prval("ipFragFails",		ip->ipFragFails);
2502 	prval("ipFragCreates",		ip->ipFragCreates);
2503 	prval("ipRoutingDiscards",	ip->ipRoutingDiscards);
2504 
2505 	prval("tcpInErrs",		ip->tcpInErrs);
2506 	prval("udpNoPorts",		ip->udpNoPorts);
2507 	prval("udpInCksumErrs",		ip->udpInCksumErrs);
2508 	prval("udpInOverflows",		ip->udpInOverflows);
2509 	prval("rawipInOverflows",	ip->rawipInOverflows);
2510 	prval("ipsecInSucceeded",	ip->ipsecInSucceeded);
2511 	prval("ipsecInFailed",		ip->ipsecInFailed);
2512 	prval("ipInIPv6",		ip->ipInIPv6);
2513 	prval("ipOutIPv6",		ip->ipOutIPv6);
2514 	prval("ipOutSwitchIPv6",	ip->ipOutSwitchIPv6);
2515 	prval_end();
2516 }
2517 
2518 static void
2519 print_icmp_stats(mib2_icmp_t *icmp)
2520 {
2521 	prval_init();
2522 	prval("icmpInMsgs",		icmp->icmpInMsgs);
2523 	prval("icmpInErrors",		icmp->icmpInErrors);
2524 	prval("icmpInCksumErrs",	icmp->icmpInCksumErrs);
2525 	prval("icmpInUnknowns",		icmp->icmpInUnknowns);
2526 	prval("icmpInDestUnreachs",	icmp->icmpInDestUnreachs);
2527 	prval("icmpInTimeExcds",	icmp->icmpInTimeExcds);
2528 	prval("icmpInParmProbs",	icmp->icmpInParmProbs);
2529 	prval("icmpInSrcQuenchs",	icmp->icmpInSrcQuenchs);
2530 	prval("icmpInRedirects",	icmp->icmpInRedirects);
2531 	prval("icmpInBadRedirects",	icmp->icmpInBadRedirects);
2532 	prval("icmpInEchos",		icmp->icmpInEchos);
2533 	prval("icmpInEchoReps",		icmp->icmpInEchoReps);
2534 	prval("icmpInTimestamps",	icmp->icmpInTimestamps);
2535 	prval("icmpInTimestampReps",	icmp->icmpInTimestampReps);
2536 	prval("icmpInAddrMasks",	icmp->icmpInAddrMasks);
2537 	prval("icmpInAddrMaskReps",	icmp->icmpInAddrMaskReps);
2538 	prval("icmpInFragNeeded",	icmp->icmpInFragNeeded);
2539 	prval("icmpOutMsgs",		icmp->icmpOutMsgs);
2540 	prval("icmpOutDrops",		icmp->icmpOutDrops);
2541 	prval("icmpOutErrors",		icmp->icmpOutErrors);
2542 	prval("icmpOutDestUnreachs",	icmp->icmpOutDestUnreachs);
2543 	prval("icmpOutTimeExcds",	icmp->icmpOutTimeExcds);
2544 	prval("icmpOutParmProbs",	icmp->icmpOutParmProbs);
2545 	prval("icmpOutSrcQuenchs",	icmp->icmpOutSrcQuenchs);
2546 	prval("icmpOutRedirects",	icmp->icmpOutRedirects);
2547 	prval("icmpOutEchos",		icmp->icmpOutEchos);
2548 	prval("icmpOutEchoReps",	icmp->icmpOutEchoReps);
2549 	prval("icmpOutTimestamps",	icmp->icmpOutTimestamps);
2550 	prval("icmpOutTimestampReps",	icmp->icmpOutTimestampReps);
2551 	prval("icmpOutAddrMasks",	icmp->icmpOutAddrMasks);
2552 	prval("icmpOutAddrMaskReps",	icmp->icmpOutAddrMaskReps);
2553 	prval("icmpOutFragNeeded",	icmp->icmpOutFragNeeded);
2554 	prval("icmpInOverflows",	icmp->icmpInOverflows);
2555 	prval_end();
2556 }
2557 
2558 static void
2559 print_ip6_stats(mib2_ipv6IfStatsEntry_t *ip6)
2560 {
2561 	prval_init();
2562 	prval("ipv6Forwarding",		ip6->ipv6Forwarding);
2563 	prval("ipv6DefaultHopLimit",	ip6->ipv6DefaultHopLimit);
2564 
2565 	prval("ipv6InReceives",		ip6->ipv6InReceives);
2566 	prval("ipv6InHdrErrors",	ip6->ipv6InHdrErrors);
2567 	prval("ipv6InTooBigErrors",	ip6->ipv6InTooBigErrors);
2568 	prval("ipv6InNoRoutes",		ip6->ipv6InNoRoutes);
2569 	prval("ipv6InAddrErrors",	ip6->ipv6InAddrErrors);
2570 	prval("ipv6InUnknownProtos",	ip6->ipv6InUnknownProtos);
2571 	prval("ipv6InTruncatedPkts",	ip6->ipv6InTruncatedPkts);
2572 	prval("ipv6InDiscards",		ip6->ipv6InDiscards);
2573 	prval("ipv6InDelivers",		ip6->ipv6InDelivers);
2574 	prval("ipv6OutForwDatagrams",	ip6->ipv6OutForwDatagrams);
2575 	prval("ipv6OutRequests",	ip6->ipv6OutRequests);
2576 	prval("ipv6OutDiscards",	ip6->ipv6OutDiscards);
2577 	prval("ipv6OutNoRoutes",	ip6->ipv6OutNoRoutes);
2578 	prval("ipv6OutFragOKs",		ip6->ipv6OutFragOKs);
2579 	prval("ipv6OutFragFails",	ip6->ipv6OutFragFails);
2580 	prval("ipv6OutFragCreates",	ip6->ipv6OutFragCreates);
2581 	prval("ipv6ReasmReqds",		ip6->ipv6ReasmReqds);
2582 	prval("ipv6ReasmOKs",		ip6->ipv6ReasmOKs);
2583 	prval("ipv6ReasmFails",		ip6->ipv6ReasmFails);
2584 	prval("ipv6InMcastPkts",	ip6->ipv6InMcastPkts);
2585 	prval("ipv6OutMcastPkts",	ip6->ipv6OutMcastPkts);
2586 	prval("ipv6ReasmDuplicates",	ip6->ipv6ReasmDuplicates);
2587 	prval("ipv6ReasmPartDups",	ip6->ipv6ReasmPartDups);
2588 	prval("ipv6ForwProhibits",	ip6->ipv6ForwProhibits);
2589 	prval("udpInCksumErrs",		ip6->udpInCksumErrs);
2590 	prval("udpInOverflows",		ip6->udpInOverflows);
2591 	prval("rawipInOverflows",	ip6->rawipInOverflows);
2592 	prval("ipv6InIPv4",		ip6->ipv6InIPv4);
2593 	prval("ipv6OutIPv4",		ip6->ipv6OutIPv4);
2594 	prval("ipv6OutSwitchIPv4",	ip6->ipv6OutSwitchIPv4);
2595 	prval_end();
2596 }
2597 
2598 static void
2599 print_icmp6_stats(mib2_ipv6IfIcmpEntry_t *icmp6)
2600 {
2601 	prval_init();
2602 	prval("icmp6InMsgs",		icmp6->ipv6IfIcmpInMsgs);
2603 	prval("icmp6InErrors",		icmp6->ipv6IfIcmpInErrors);
2604 	prval("icmp6InDestUnreachs",	icmp6->ipv6IfIcmpInDestUnreachs);
2605 	prval("icmp6InAdminProhibs",	icmp6->ipv6IfIcmpInAdminProhibs);
2606 	prval("icmp6InTimeExcds",	icmp6->ipv6IfIcmpInTimeExcds);
2607 	prval("icmp6InParmProblems",	icmp6->ipv6IfIcmpInParmProblems);
2608 	prval("icmp6InPktTooBigs",	icmp6->ipv6IfIcmpInPktTooBigs);
2609 	prval("icmp6InEchos",		icmp6->ipv6IfIcmpInEchos);
2610 	prval("icmp6InEchoReplies",	icmp6->ipv6IfIcmpInEchoReplies);
2611 	prval("icmp6InRouterSols",	icmp6->ipv6IfIcmpInRouterSolicits);
2612 	prval("icmp6InRouterAds",
2613 	    icmp6->ipv6IfIcmpInRouterAdvertisements);
2614 	prval("icmp6InNeighborSols",	icmp6->ipv6IfIcmpInNeighborSolicits);
2615 	prval("icmp6InNeighborAds",
2616 	    icmp6->ipv6IfIcmpInNeighborAdvertisements);
2617 	prval("icmp6InRedirects",	icmp6->ipv6IfIcmpInRedirects);
2618 	prval("icmp6InBadRedirects",	icmp6->ipv6IfIcmpInBadRedirects);
2619 	prval("icmp6InGroupQueries",	icmp6->ipv6IfIcmpInGroupMembQueries);
2620 	prval("icmp6InGroupResps",	icmp6->ipv6IfIcmpInGroupMembResponses);
2621 	prval("icmp6InGroupReds",	icmp6->ipv6IfIcmpInGroupMembReductions);
2622 	prval("icmp6InOverflows",	icmp6->ipv6IfIcmpInOverflows);
2623 	prval_end();
2624 	prval_init();
2625 	prval("icmp6OutMsgs",		icmp6->ipv6IfIcmpOutMsgs);
2626 	prval("icmp6OutErrors",		icmp6->ipv6IfIcmpOutErrors);
2627 	prval("icmp6OutDestUnreachs",	icmp6->ipv6IfIcmpOutDestUnreachs);
2628 	prval("icmp6OutAdminProhibs",	icmp6->ipv6IfIcmpOutAdminProhibs);
2629 	prval("icmp6OutTimeExcds",	icmp6->ipv6IfIcmpOutTimeExcds);
2630 	prval("icmp6OutParmProblems",	icmp6->ipv6IfIcmpOutParmProblems);
2631 	prval("icmp6OutPktTooBigs",	icmp6->ipv6IfIcmpOutPktTooBigs);
2632 	prval("icmp6OutEchos",		icmp6->ipv6IfIcmpOutEchos);
2633 	prval("icmp6OutEchoReplies",	icmp6->ipv6IfIcmpOutEchoReplies);
2634 	prval("icmp6OutRouterSols",	icmp6->ipv6IfIcmpOutRouterSolicits);
2635 	prval("icmp6OutRouterAds",
2636 	    icmp6->ipv6IfIcmpOutRouterAdvertisements);
2637 	prval("icmp6OutNeighborSols",	icmp6->ipv6IfIcmpOutNeighborSolicits);
2638 	prval("icmp6OutNeighborAds",
2639 	    icmp6->ipv6IfIcmpOutNeighborAdvertisements);
2640 	prval("icmp6OutRedirects",	icmp6->ipv6IfIcmpOutRedirects);
2641 	prval("icmp6OutGroupQueries",	icmp6->ipv6IfIcmpOutGroupMembQueries);
2642 	prval("icmp6OutGroupResps",
2643 	    icmp6->ipv6IfIcmpOutGroupMembResponses);
2644 	prval("icmp6OutGroupReds",
2645 	    icmp6->ipv6IfIcmpOutGroupMembReductions);
2646 	prval_end();
2647 }
2648 
2649 static void
2650 print_sctp_stats(mib2_sctp_t *sctp)
2651 {
2652 	prval_init();
2653 	pr_sctp_rtoalgo("sctpRtoAlgorithm", sctp->sctpRtoAlgorithm);
2654 	prval("sctpRtoMin",		sctp->sctpRtoMin);
2655 	prval("sctpRtoMax",		sctp->sctpRtoMax);
2656 	prval("sctpRtoInitial",		sctp->sctpRtoInitial);
2657 	pr_int_val("sctpMaxAssocs",	sctp->sctpMaxAssocs);
2658 	prval("sctpValCookieLife",	sctp->sctpValCookieLife);
2659 	prval("sctpMaxInitRetr",	sctp->sctpMaxInitRetr);
2660 	prval("sctpCurrEstab",		sctp->sctpCurrEstab);
2661 	prval("sctpActiveEstab",	sctp->sctpActiveEstab);
2662 	prval("sctpPassiveEstab",	sctp->sctpPassiveEstab);
2663 	prval("sctpAborted",		sctp->sctpAborted);
2664 	prval("sctpShutdowns",		sctp->sctpShutdowns);
2665 	prval("sctpOutOfBlue",		sctp->sctpOutOfBlue);
2666 	prval("sctpChecksumError",	sctp->sctpChecksumError);
2667 	prval64("sctpOutCtrlChunks",	sctp->sctpOutCtrlChunks);
2668 	prval64("sctpOutOrderChunks",	sctp->sctpOutOrderChunks);
2669 	prval64("sctpOutUnorderChunks",	sctp->sctpOutUnorderChunks);
2670 	prval64("sctpRetransChunks",	sctp->sctpRetransChunks);
2671 	prval("sctpOutAck",		sctp->sctpOutAck);
2672 	prval("sctpOutAckDelayed",	sctp->sctpOutAckDelayed);
2673 	prval("sctpOutWinUpdate",	sctp->sctpOutWinUpdate);
2674 	prval("sctpOutFastRetrans",	sctp->sctpOutFastRetrans);
2675 	prval("sctpOutWinProbe",	sctp->sctpOutWinProbe);
2676 	prval64("sctpInCtrlChunks",	sctp->sctpInCtrlChunks);
2677 	prval64("sctpInOrderChunks",	sctp->sctpInOrderChunks);
2678 	prval64("sctpInUnorderChunks",	sctp->sctpInUnorderChunks);
2679 	prval("sctpInAck",		sctp->sctpInAck);
2680 	prval("sctpInDupAck",		sctp->sctpInDupAck);
2681 	prval("sctpInAckUnsent",	sctp->sctpInAckUnsent);
2682 	prval64("sctpFragUsrMsgs",	sctp->sctpFragUsrMsgs);
2683 	prval64("sctpReasmUsrMsgs",	sctp->sctpReasmUsrMsgs);
2684 	prval64("sctpOutSCTPPkts",	sctp->sctpOutSCTPPkts);
2685 	prval64("sctpInSCTPPkts",	sctp->sctpInSCTPPkts);
2686 	prval("sctpInInvalidCookie",	sctp->sctpInInvalidCookie);
2687 	prval("sctpTimRetrans",		sctp->sctpTimRetrans);
2688 	prval("sctpTimRetransDrop",	sctp->sctpTimRetransDrop);
2689 	prval("sctpTimHearBeatProbe",	sctp->sctpTimHeartBeatProbe);
2690 	prval("sctpTimHearBeatDrop",	sctp->sctpTimHeartBeatDrop);
2691 	prval("sctpListenDrop",		sctp->sctpListenDrop);
2692 	prval("sctpInClosed",		sctp->sctpInClosed);
2693 	prval_end();
2694 }
2695 
2696 static void
2697 print_tcp_stats(mib2_tcp_t *tcp)
2698 {
2699 	prval_init();
2700 	pr_int_val("tcpRtoAlgorithm",	tcp->tcpRtoAlgorithm);
2701 	pr_int_val("tcpRtoMin",		tcp->tcpRtoMin);
2702 	pr_int_val("tcpRtoMax",		tcp->tcpRtoMax);
2703 	pr_int_val("tcpMaxConn",	tcp->tcpMaxConn);
2704 	prval("tcpActiveOpens",		tcp->tcpActiveOpens);
2705 	prval("tcpPassiveOpens",	tcp->tcpPassiveOpens);
2706 	prval("tcpAttemptFails",	tcp->tcpAttemptFails);
2707 	prval("tcpEstabResets",		tcp->tcpEstabResets);
2708 	prval("tcpCurrEstab",		tcp->tcpCurrEstab);
2709 	prval64("tcpOutSegs",		tcp->tcpHCOutSegs);
2710 	prval("tcpOutDataSegs",		tcp->tcpOutDataSegs);
2711 	prval("tcpOutDataBytes",	tcp->tcpOutDataBytes);
2712 	prval("tcpRetransSegs",		tcp->tcpRetransSegs);
2713 	prval("tcpRetransBytes",	tcp->tcpRetransBytes);
2714 	prval("tcpOutAck",		tcp->tcpOutAck);
2715 	prval("tcpOutAckDelayed",	tcp->tcpOutAckDelayed);
2716 	prval("tcpOutUrg",		tcp->tcpOutUrg);
2717 	prval("tcpOutWinUpdate",	tcp->tcpOutWinUpdate);
2718 	prval("tcpOutWinProbe",		tcp->tcpOutWinProbe);
2719 	prval("tcpOutControl",		tcp->tcpOutControl);
2720 	prval("tcpOutRsts",		tcp->tcpOutRsts);
2721 	prval("tcpOutFastRetrans",	tcp->tcpOutFastRetrans);
2722 	prval64("tcpInSegs",		tcp->tcpHCInSegs);
2723 	prval_end();
2724 	prval("tcpInAckSegs",		tcp->tcpInAckSegs);
2725 	prval("tcpInAckBytes",		tcp->tcpInAckBytes);
2726 	prval("tcpInDupAck",		tcp->tcpInDupAck);
2727 	prval("tcpInAckUnsent",		tcp->tcpInAckUnsent);
2728 	prval("tcpInInorderSegs",	tcp->tcpInDataInorderSegs);
2729 	prval("tcpInInorderBytes",	tcp->tcpInDataInorderBytes);
2730 	prval("tcpInUnorderSegs",	tcp->tcpInDataUnorderSegs);
2731 	prval("tcpInUnorderBytes",	tcp->tcpInDataUnorderBytes);
2732 	prval("tcpInDupSegs",		tcp->tcpInDataDupSegs);
2733 	prval("tcpInDupBytes",		tcp->tcpInDataDupBytes);
2734 	prval("tcpInPartDupSegs",	tcp->tcpInDataPartDupSegs);
2735 	prval("tcpInPartDupBytes",	tcp->tcpInDataPartDupBytes);
2736 	prval("tcpInPastWinSegs",	tcp->tcpInDataPastWinSegs);
2737 	prval("tcpInPastWinBytes",	tcp->tcpInDataPastWinBytes);
2738 	prval("tcpInWinProbe",		tcp->tcpInWinProbe);
2739 	prval("tcpInWinUpdate",		tcp->tcpInWinUpdate);
2740 	prval("tcpInClosed",		tcp->tcpInClosed);
2741 	prval("tcpRttNoUpdate",		tcp->tcpRttNoUpdate);
2742 	prval("tcpRttUpdate",		tcp->tcpRttUpdate);
2743 	prval("tcpTimRetrans",		tcp->tcpTimRetrans);
2744 	prval("tcpTimRetransDrop",	tcp->tcpTimRetransDrop);
2745 	prval("tcpTimKeepalive",	tcp->tcpTimKeepalive);
2746 	prval("tcpTimKeepaliveProbe",	tcp->tcpTimKeepaliveProbe);
2747 	prval("tcpTimKeepaliveDrop",	tcp->tcpTimKeepaliveDrop);
2748 	prval("tcpListenDrop",		tcp->tcpListenDrop);
2749 	prval("tcpListenDropQ0",	tcp->tcpListenDropQ0);
2750 	prval("tcpHalfOpenDrop",	tcp->tcpHalfOpenDrop);
2751 	prval("tcpOutSackRetrans",	tcp->tcpOutSackRetransSegs);
2752 	prval_end();
2753 
2754 }
2755 
2756 static void
2757 print_udp_stats(mib2_udp_t *udp)
2758 {
2759 	prval_init();
2760 	prval64("udpInDatagrams",	udp->udpHCInDatagrams);
2761 	prval("udpInErrors",		udp->udpInErrors);
2762 	prval64("udpOutDatagrams",	udp->udpHCOutDatagrams);
2763 	prval("udpOutErrors",		udp->udpOutErrors);
2764 	prval_end();
2765 }
2766 
2767 static void
2768 print_rawip_stats(mib2_rawip_t *rawip)
2769 {
2770 	prval_init();
2771 	prval("rawipInDatagrams",	rawip->rawipInDatagrams);
2772 	prval("rawipInErrors",		rawip->rawipInErrors);
2773 	prval("rawipInCksumErrs",	rawip->rawipInCksumErrs);
2774 	prval("rawipOutDatagrams",	rawip->rawipOutDatagrams);
2775 	prval("rawipOutErrors",		rawip->rawipOutErrors);
2776 	prval_end();
2777 }
2778 
2779 void
2780 print_igmp_stats(struct igmpstat *igps)
2781 {
2782 	(void) printf(" %10u message%s received\n",
2783 	    igps->igps_rcv_total, PLURAL(igps->igps_rcv_total));
2784 	(void) printf(" %10u message%s received with too few bytes\n",
2785 	    igps->igps_rcv_tooshort, PLURAL(igps->igps_rcv_tooshort));
2786 	(void) printf(" %10u message%s received with bad checksum\n",
2787 	    igps->igps_rcv_badsum, PLURAL(igps->igps_rcv_badsum));
2788 	(void) printf(" %10u membership quer%s received\n",
2789 	    igps->igps_rcv_queries, PLURALY(igps->igps_rcv_queries));
2790 	(void) printf(" %10u membership quer%s received with invalid "
2791 	    "field(s)\n",
2792 	    igps->igps_rcv_badqueries, PLURALY(igps->igps_rcv_badqueries));
2793 	(void) printf(" %10u membership report%s received\n",
2794 	    igps->igps_rcv_reports, PLURAL(igps->igps_rcv_reports));
2795 	(void) printf(" %10u membership report%s received with invalid "
2796 	    "field(s)\n",
2797 	    igps->igps_rcv_badreports, PLURAL(igps->igps_rcv_badreports));
2798 	(void) printf(" %10u membership report%s received for groups to "
2799 	    "which we belong\n",
2800 	    igps->igps_rcv_ourreports, PLURAL(igps->igps_rcv_ourreports));
2801 	(void) printf(" %10u membership report%s sent\n",
2802 	    igps->igps_snd_reports, PLURAL(igps->igps_snd_reports));
2803 }
2804 
2805 static void
2806 print_mrt_stats(struct mrtstat *mrts)
2807 {
2808 	(void) puts("DVMRP multicast routing:");
2809 	(void) printf(" %10u hit%s - kernel forwarding cache hits\n",
2810 	    mrts->mrts_mfc_hits, PLURAL(mrts->mrts_mfc_hits));
2811 	(void) printf(" %10u miss%s - kernel forwarding cache misses\n",
2812 	    mrts->mrts_mfc_misses, PLURALES(mrts->mrts_mfc_misses));
2813 	(void) printf(" %10u packet%s potentially forwarded\n",
2814 	    mrts->mrts_fwd_in, PLURAL(mrts->mrts_fwd_in));
2815 	(void) printf(" %10u packet%s actually sent out\n",
2816 	    mrts->mrts_fwd_out, PLURAL(mrts->mrts_fwd_out));
2817 	(void) printf(" %10u upcall%s - upcalls made to mrouted\n",
2818 	    mrts->mrts_upcalls, PLURAL(mrts->mrts_upcalls));
2819 	(void) printf(" %10u packet%s not sent out due to lack of resources\n",
2820 	    mrts->mrts_fwd_drop, PLURAL(mrts->mrts_fwd_drop));
2821 	(void) printf(" %10u datagram%s with malformed tunnel options\n",
2822 	    mrts->mrts_bad_tunnel, PLURAL(mrts->mrts_bad_tunnel));
2823 	(void) printf(" %10u datagram%s with no room for tunnel options\n",
2824 	    mrts->mrts_cant_tunnel, PLURAL(mrts->mrts_cant_tunnel));
2825 	(void) printf(" %10u datagram%s arrived on wrong interface\n",
2826 	    mrts->mrts_wrong_if, PLURAL(mrts->mrts_wrong_if));
2827 	(void) printf(" %10u datagram%s dropped due to upcall Q overflow\n",
2828 	    mrts->mrts_upq_ovflw, PLURAL(mrts->mrts_upq_ovflw));
2829 	(void) printf(" %10u datagram%s cleaned up by the cache\n",
2830 	    mrts->mrts_cache_cleanups, PLURAL(mrts->mrts_cache_cleanups));
2831 	(void) printf(" %10u datagram%s dropped selectively by ratelimiter\n",
2832 	    mrts->mrts_drop_sel, PLURAL(mrts->mrts_drop_sel));
2833 	(void) printf(" %10u datagram%s dropped - bucket Q overflow\n",
2834 	    mrts->mrts_q_overflow, PLURAL(mrts->mrts_q_overflow));
2835 	(void) printf(" %10u datagram%s dropped - larger than bkt size\n",
2836 	    mrts->mrts_pkt2large, PLURAL(mrts->mrts_pkt2large));
2837 	(void) printf("\nPIM multicast routing:\n");
2838 	(void) printf(" %10u datagram%s dropped - bad version number\n",
2839 	    mrts->mrts_pim_badversion, PLURAL(mrts->mrts_pim_badversion));
2840 	(void) printf(" %10u datagram%s dropped - bad checksum\n",
2841 	    mrts->mrts_pim_rcv_badcsum, PLURAL(mrts->mrts_pim_rcv_badcsum));
2842 	(void) printf(" %10u datagram%s dropped - bad register packets\n",
2843 	    mrts->mrts_pim_badregisters, PLURAL(mrts->mrts_pim_badregisters));
2844 	(void) printf(
2845 	    " %10u datagram%s potentially forwarded - register packets\n",
2846 	    mrts->mrts_pim_regforwards, PLURAL(mrts->mrts_pim_regforwards));
2847 	(void) printf(" %10u datagram%s dropped - register send drops\n",
2848 	    mrts->mrts_pim_regsend_drops, PLURAL(mrts->mrts_pim_regsend_drops));
2849 	(void) printf(" %10u datagram%s dropped - packet malformed\n",
2850 	    mrts->mrts_pim_malformed, PLURAL(mrts->mrts_pim_malformed));
2851 	(void) printf(" %10u datagram%s dropped - no memory to forward\n",
2852 	    mrts->mrts_pim_nomemory, PLURAL(mrts->mrts_pim_nomemory));
2853 }
2854 
2855 static void
2856 sum_ip6_stats(mib2_ipv6IfStatsEntry_t *ip6, mib2_ipv6IfStatsEntry_t *sum6)
2857 {
2858 	/* First few are not additive */
2859 	sum6->ipv6Forwarding = ip6->ipv6Forwarding;
2860 	sum6->ipv6DefaultHopLimit = ip6->ipv6DefaultHopLimit;
2861 
2862 	sum6->ipv6InReceives += ip6->ipv6InReceives;
2863 	sum6->ipv6InHdrErrors += ip6->ipv6InHdrErrors;
2864 	sum6->ipv6InTooBigErrors += ip6->ipv6InTooBigErrors;
2865 	sum6->ipv6InNoRoutes += ip6->ipv6InNoRoutes;
2866 	sum6->ipv6InAddrErrors += ip6->ipv6InAddrErrors;
2867 	sum6->ipv6InUnknownProtos += ip6->ipv6InUnknownProtos;
2868 	sum6->ipv6InTruncatedPkts += ip6->ipv6InTruncatedPkts;
2869 	sum6->ipv6InDiscards += ip6->ipv6InDiscards;
2870 	sum6->ipv6InDelivers += ip6->ipv6InDelivers;
2871 	sum6->ipv6OutForwDatagrams += ip6->ipv6OutForwDatagrams;
2872 	sum6->ipv6OutRequests += ip6->ipv6OutRequests;
2873 	sum6->ipv6OutDiscards += ip6->ipv6OutDiscards;
2874 	sum6->ipv6OutFragOKs += ip6->ipv6OutFragOKs;
2875 	sum6->ipv6OutFragFails += ip6->ipv6OutFragFails;
2876 	sum6->ipv6OutFragCreates += ip6->ipv6OutFragCreates;
2877 	sum6->ipv6ReasmReqds += ip6->ipv6ReasmReqds;
2878 	sum6->ipv6ReasmOKs += ip6->ipv6ReasmOKs;
2879 	sum6->ipv6ReasmFails += ip6->ipv6ReasmFails;
2880 	sum6->ipv6InMcastPkts += ip6->ipv6InMcastPkts;
2881 	sum6->ipv6OutMcastPkts += ip6->ipv6OutMcastPkts;
2882 	sum6->ipv6OutNoRoutes += ip6->ipv6OutNoRoutes;
2883 	sum6->ipv6ReasmDuplicates += ip6->ipv6ReasmDuplicates;
2884 	sum6->ipv6ReasmPartDups += ip6->ipv6ReasmPartDups;
2885 	sum6->ipv6ForwProhibits += ip6->ipv6ForwProhibits;
2886 	sum6->udpInCksumErrs += ip6->udpInCksumErrs;
2887 	sum6->udpInOverflows += ip6->udpInOverflows;
2888 	sum6->rawipInOverflows += ip6->rawipInOverflows;
2889 }
2890 
2891 static void
2892 sum_icmp6_stats(mib2_ipv6IfIcmpEntry_t *icmp6, mib2_ipv6IfIcmpEntry_t *sum6)
2893 {
2894 	sum6->ipv6IfIcmpInMsgs += icmp6->ipv6IfIcmpInMsgs;
2895 	sum6->ipv6IfIcmpInErrors += icmp6->ipv6IfIcmpInErrors;
2896 	sum6->ipv6IfIcmpInDestUnreachs += icmp6->ipv6IfIcmpInDestUnreachs;
2897 	sum6->ipv6IfIcmpInAdminProhibs += icmp6->ipv6IfIcmpInAdminProhibs;
2898 	sum6->ipv6IfIcmpInTimeExcds += icmp6->ipv6IfIcmpInTimeExcds;
2899 	sum6->ipv6IfIcmpInParmProblems += icmp6->ipv6IfIcmpInParmProblems;
2900 	sum6->ipv6IfIcmpInPktTooBigs += icmp6->ipv6IfIcmpInPktTooBigs;
2901 	sum6->ipv6IfIcmpInEchos += icmp6->ipv6IfIcmpInEchos;
2902 	sum6->ipv6IfIcmpInEchoReplies += icmp6->ipv6IfIcmpInEchoReplies;
2903 	sum6->ipv6IfIcmpInRouterSolicits += icmp6->ipv6IfIcmpInRouterSolicits;
2904 	sum6->ipv6IfIcmpInRouterAdvertisements +=
2905 	    icmp6->ipv6IfIcmpInRouterAdvertisements;
2906 	sum6->ipv6IfIcmpInNeighborSolicits +=
2907 	    icmp6->ipv6IfIcmpInNeighborSolicits;
2908 	sum6->ipv6IfIcmpInNeighborAdvertisements +=
2909 	    icmp6->ipv6IfIcmpInNeighborAdvertisements;
2910 	sum6->ipv6IfIcmpInRedirects += icmp6->ipv6IfIcmpInRedirects;
2911 	sum6->ipv6IfIcmpInGroupMembQueries +=
2912 	    icmp6->ipv6IfIcmpInGroupMembQueries;
2913 	sum6->ipv6IfIcmpInGroupMembResponses +=
2914 	    icmp6->ipv6IfIcmpInGroupMembResponses;
2915 	sum6->ipv6IfIcmpInGroupMembReductions +=
2916 	    icmp6->ipv6IfIcmpInGroupMembReductions;
2917 	sum6->ipv6IfIcmpOutMsgs += icmp6->ipv6IfIcmpOutMsgs;
2918 	sum6->ipv6IfIcmpOutErrors += icmp6->ipv6IfIcmpOutErrors;
2919 	sum6->ipv6IfIcmpOutDestUnreachs += icmp6->ipv6IfIcmpOutDestUnreachs;
2920 	sum6->ipv6IfIcmpOutAdminProhibs += icmp6->ipv6IfIcmpOutAdminProhibs;
2921 	sum6->ipv6IfIcmpOutTimeExcds += icmp6->ipv6IfIcmpOutTimeExcds;
2922 	sum6->ipv6IfIcmpOutParmProblems += icmp6->ipv6IfIcmpOutParmProblems;
2923 	sum6->ipv6IfIcmpOutPktTooBigs += icmp6->ipv6IfIcmpOutPktTooBigs;
2924 	sum6->ipv6IfIcmpOutEchos += icmp6->ipv6IfIcmpOutEchos;
2925 	sum6->ipv6IfIcmpOutEchoReplies += icmp6->ipv6IfIcmpOutEchoReplies;
2926 	sum6->ipv6IfIcmpOutRouterSolicits +=
2927 	    icmp6->ipv6IfIcmpOutRouterSolicits;
2928 	sum6->ipv6IfIcmpOutRouterAdvertisements +=
2929 	    icmp6->ipv6IfIcmpOutRouterAdvertisements;
2930 	sum6->ipv6IfIcmpOutNeighborSolicits +=
2931 	    icmp6->ipv6IfIcmpOutNeighborSolicits;
2932 	sum6->ipv6IfIcmpOutNeighborAdvertisements +=
2933 	    icmp6->ipv6IfIcmpOutNeighborAdvertisements;
2934 	sum6->ipv6IfIcmpOutRedirects += icmp6->ipv6IfIcmpOutRedirects;
2935 	sum6->ipv6IfIcmpOutGroupMembQueries +=
2936 	    icmp6->ipv6IfIcmpOutGroupMembQueries;
2937 	sum6->ipv6IfIcmpOutGroupMembResponses +=
2938 	    icmp6->ipv6IfIcmpOutGroupMembResponses;
2939 	sum6->ipv6IfIcmpOutGroupMembReductions +=
2940 	    icmp6->ipv6IfIcmpOutGroupMembReductions;
2941 	sum6->ipv6IfIcmpInOverflows += icmp6->ipv6IfIcmpInOverflows;
2942 }
2943 
2944 /* ----------------------------- MRT_STAT_REPORT --------------------------- */
2945 
2946 static void
2947 mrt_stat_report(mib_item_t *curritem)
2948 {
2949 	int	jtemp = 0;
2950 	mib_item_t *tempitem;
2951 
2952 	if (!(family_selected(AF_INET)))
2953 		return;
2954 
2955 	(void) putchar('\n');
2956 	for (tempitem = curritem;
2957 	    tempitem;
2958 	    tempitem = tempitem->next_item) {
2959 		if (Xflag) {
2960 			(void) printf("[%4d] Group = %d, mib_id = %d, "
2961 			    "length = %d, valp = 0x%p\n",
2962 			    jtemp++, tempitem->group, tempitem->mib_id,
2963 			    tempitem->length, tempitem->valp);
2964 		}
2965 
2966 		if (tempitem->mib_id == 0) {
2967 			switch (tempitem->group) {
2968 			case EXPER_DVMRP: {
2969 				struct mrtstat	*mrts;
2970 				mrts = (struct mrtstat *)tempitem->valp;
2971 
2972 				if (!(family_selected(AF_INET)))
2973 					continue;
2974 
2975 				print_mrt_stats(mrts);
2976 				break;
2977 			}
2978 			}
2979 		}
2980 	}
2981 	(void) putchar('\n');
2982 	(void) fflush(stdout);
2983 }
2984 
2985 /*
2986  * if_stat_total() - Computes totals for interface statistics
2987  *                   and returns result by updating sumstats.
2988  */
2989 static void
2990 if_stat_total(struct ifstat *oldstats, struct ifstat *newstats,
2991     struct ifstat *sumstats)
2992 {
2993 	sumstats->ipackets += newstats->ipackets - oldstats->ipackets;
2994 	sumstats->opackets += newstats->opackets - oldstats->opackets;
2995 	sumstats->ierrors += newstats->ierrors - oldstats->ierrors;
2996 	sumstats->oerrors += newstats->oerrors - oldstats->oerrors;
2997 	sumstats->collisions += newstats->collisions - oldstats->collisions;
2998 }
2999 
3000 /* --------------------- IF_REPORT (netstat -i)  -------------------------- */
3001 
3002 static struct	ifstat	zerostat = {
3003 	0LL, 0LL, 0LL, 0LL, 0LL
3004 };
3005 
3006 static void
3007 if_report(mib_item_t *item, char *matchname,
3008     int Iflag_only, boolean_t once_only)
3009 {
3010 	static boolean_t	reentry = B_FALSE;
3011 	boolean_t		alreadydone = B_FALSE;
3012 	int			jtemp = 0;
3013 	uint32_t		ifindex_v4 = 0;
3014 	uint32_t		ifindex_v6 = 0;
3015 	boolean_t		first_header = B_TRUE;
3016 
3017 	for (; item; item = item->next_item) {
3018 		if (Xflag) {
3019 			(void) printf("[%4d] Group = %d, mib_id = %d, "
3020 			    "length = %d, valp = 0x%p\n", jtemp++,
3021 			    item->group, item->mib_id, item->length,
3022 			    item->valp);
3023 		}
3024 
3025 		switch (item->group) {
3026 		case MIB2_IP:
3027 		if (item->mib_id != MIB2_IP_ADDR ||
3028 		    !family_selected(AF_INET))
3029 			continue;
3030 		{
3031 			static struct ifstat	old = {0L, 0L, 0L, 0L, 0L};
3032 			static struct ifstat	new = {0L, 0L, 0L, 0L, 0L};
3033 			struct ifstat		sum;
3034 			struct iflist		*newlist = NULL;
3035 			static struct iflist	*oldlist = NULL;
3036 			kstat_t	 *ksp;
3037 
3038 			if (once_only) {
3039 				char    ifname[LIFNAMSIZ + 1];
3040 				char    logintname[LIFNAMSIZ + 1];
3041 				mib2_ipAddrEntry_t *ap;
3042 				struct ifstat	stat = {0L, 0L, 0L, 0L, 0L};
3043 				boolean_t	first = B_TRUE;
3044 				uint32_t	new_ifindex;
3045 
3046 				if (Xflag)
3047 					(void) printf("if_report: %d items\n",
3048 					    (item->length)
3049 					    / sizeof (mib2_ipAddrEntry_t));
3050 
3051 				for (ap = (mib2_ipAddrEntry_t *)item->valp;
3052 				    (char *)ap < (char *)item->valp
3053 				    + item->length;
3054 				    ap++) {
3055 					(void) octetstr(&ap->ipAdEntIfIndex,
3056 					    'a', logintname,
3057 					    sizeof (logintname));
3058 					(void) strcpy(ifname, logintname);
3059 					(void) strtok(ifname, ":");
3060 					if (matchname != NULL &&
3061 					    strcmp(matchname, ifname) != 0 &&
3062 					    strcmp(matchname, logintname) != 0)
3063 						continue;
3064 					new_ifindex =
3065 					    if_nametoindex(logintname);
3066 					/*
3067 					 * First lookup the "link" kstats in
3068 					 * case the link is renamed. Then
3069 					 * fallback to the legacy kstats for
3070 					 * those non-GLDv3 links.
3071 					 */
3072 					if (new_ifindex != ifindex_v4 &&
3073 					    (((ksp = kstat_lookup(kc, "link", 0,
3074 					    ifname)) != NULL) ||
3075 					    ((ksp = kstat_lookup(kc, NULL, -1,
3076 					    ifname)) != NULL))) {
3077 						(void) safe_kstat_read(kc, ksp,
3078 						    NULL);
3079 						stat.ipackets =
3080 						    kstat_named_value(ksp,
3081 						    "ipackets");
3082 						stat.ierrors =
3083 						    kstat_named_value(ksp,
3084 						    "ierrors");
3085 						stat.opackets =
3086 						    kstat_named_value(ksp,
3087 						    "opackets");
3088 						stat.oerrors =
3089 						    kstat_named_value(ksp,
3090 						    "oerrors");
3091 						stat.collisions =
3092 						    kstat_named_value(ksp,
3093 						    "collisions");
3094 						if (first) {
3095 							if (!first_header)
3096 								(void) putchar(
3097 								    '\n');
3098 							first_header = B_FALSE;
3099 							(void) printf(
3100 							    "%-5.5s %-5.5s"
3101 							    "%-13.13s %-14.14s "
3102 							    "%-6.6s %-5.5s "
3103 							    "%-6.6s %-5.5s "
3104 							    "%-6.6s %-6.6s\n",
3105 							    "Name", "Mtu",
3106 							    "Net/Dest",
3107 							    "Address", "Ipkts",
3108 							    "Ierrs", "Opkts",
3109 							    "Oerrs", "Collis",
3110 							    "Queue");
3111 							first = B_FALSE;
3112 						}
3113 						if_report_ip4(ap, ifname,
3114 						    logintname, &stat, B_TRUE);
3115 						ifindex_v4 = new_ifindex;
3116 					} else {
3117 						if_report_ip4(ap, ifname,
3118 						    logintname, &stat, B_FALSE);
3119 					}
3120 				}
3121 			} else if (!alreadydone) {
3122 				char    ifname[LIFNAMSIZ + 1];
3123 				char    buf[LIFNAMSIZ + 1];
3124 				mib2_ipAddrEntry_t *ap;
3125 				struct ifstat   t;
3126 				struct iflist	*tlp = NULL;
3127 				struct iflist	**nextnew = &newlist;
3128 				struct iflist	*walkold;
3129 				struct iflist	*cleanlist;
3130 				boolean_t	found_if = B_FALSE;
3131 
3132 				alreadydone = B_TRUE; /* ignore other case */
3133 
3134 				/*
3135 				 * Check if there is anything to do.
3136 				 */
3137 				if (item->length <
3138 				    sizeof (mib2_ipAddrEntry_t)) {
3139 					fail(0, "No compatible interfaces");
3140 				}
3141 
3142 				/*
3143 				 * Find the "right" entry:
3144 				 * If an interface name to match has been
3145 				 * supplied then try and find it, otherwise
3146 				 * match the first non-loopback interface found.
3147 				 * Use lo0 if all else fails.
3148 				 */
3149 				for (ap = (mib2_ipAddrEntry_t *)item->valp;
3150 				    (char *)ap < (char *)item->valp
3151 				    + item->length;
3152 				    ap++) {
3153 					(void) octetstr(&ap->ipAdEntIfIndex,
3154 					    'a', ifname, sizeof (ifname));
3155 					(void) strtok(ifname, ":");
3156 
3157 					if (matchname) {
3158 						if (strcmp(matchname,
3159 						    ifname) == 0) {
3160 							found_if = B_TRUE;
3161 							break;
3162 						}
3163 					} else if (strcmp(ifname, "lo0") != 0)
3164 						break;
3165 				}
3166 
3167 				if (matchname == NULL) {
3168 					matchname = ifname;
3169 				} else {
3170 					if (!found_if)
3171 						fail(0, "-I: %s no such "
3172 						    "interface.", matchname);
3173 				}
3174 
3175 				if (Iflag_only == 0 || !reentry) {
3176 					(void) printf("    input   %-6.6s    "
3177 					    "output	",
3178 					    matchname);
3179 					(void) printf("   input  (Total)    "
3180 					"output\n");
3181 					(void) printf("%-7.7s %-5.5s %-7.7s "
3182 					    "%-5.5s %-6.6s ",
3183 					    "packets", "errs", "packets",
3184 					    "errs", "colls");
3185 					(void) printf("%-7.7s %-5.5s %-7.7s "
3186 					    "%-5.5s %-6.6s\n",
3187 					    "packets", "errs", "packets",
3188 					    "errs", "colls");
3189 				}
3190 
3191 				sum = zerostat;
3192 
3193 				for (ap = (mib2_ipAddrEntry_t *)item->valp;
3194 				    (char *)ap < (char *)item->valp
3195 				    + item->length;
3196 				    ap++) {
3197 					(void) octetstr(&ap->ipAdEntIfIndex,
3198 					    'a', buf, sizeof (buf));
3199 					(void) strtok(buf, ":");
3200 
3201 					/*
3202 					 * We have reduced the IP interface
3203 					 * name, which could have been a
3204 					 * logical, down to a name suitable
3205 					 * for use with kstats.
3206 					 * We treat this name as unique and
3207 					 * only collate statistics for it once
3208 					 * per pass. This is to avoid falsely
3209 					 * amplifying these statistics by the
3210 					 * the number of logical instances.
3211 					 */
3212 					if ((tlp != NULL) &&
3213 					    ((strcmp(buf, tlp->ifname) == 0))) {
3214 						continue;
3215 					}
3216 
3217 					/*
3218 					 * First lookup the "link" kstats in
3219 					 * case the link is renamed. Then
3220 					 * fallback to the legacy kstats for
3221 					 * those non-GLDv3 links.
3222 					 */
3223 					if (((ksp = kstat_lookup(kc, "link",
3224 					    0, buf)) != NULL ||
3225 					    (ksp = kstat_lookup(kc, NULL, -1,
3226 					    buf)) != NULL) && (ksp->ks_type ==
3227 					    KSTAT_TYPE_NAMED)) {
3228 						(void) safe_kstat_read(kc, ksp,
3229 						    NULL);
3230 					}
3231 
3232 					t.ipackets = kstat_named_value(ksp,
3233 					    "ipackets");
3234 					t.ierrors = kstat_named_value(ksp,
3235 					    "ierrors");
3236 					t.opackets = kstat_named_value(ksp,
3237 					    "opackets");
3238 					t.oerrors = kstat_named_value(ksp,
3239 					    "oerrors");
3240 					t.collisions = kstat_named_value(ksp,
3241 					    "collisions");
3242 
3243 					if (strcmp(buf, matchname) == 0)
3244 						new = t;
3245 
3246 					/* Build the interface list */
3247 
3248 					tlp = malloc(sizeof (struct iflist));
3249 					(void) strlcpy(tlp->ifname, buf,
3250 					    sizeof (tlp->ifname));
3251 					tlp->tot = t;
3252 					*nextnew = tlp;
3253 					nextnew = &tlp->next_if;
3254 
3255 					/*
3256 					 * First time through.
3257 					 * Just add up the interface stats.
3258 					 */
3259 
3260 					if (oldlist == NULL) {
3261 						if_stat_total(&zerostat,
3262 						    &t, &sum);
3263 						continue;
3264 					}
3265 
3266 					/*
3267 					 * Walk old list for the interface.
3268 					 *
3269 					 * If found, add difference to total.
3270 					 *
3271 					 * If not, an interface has been plumbed
3272 					 * up.  In this case, we will simply
3273 					 * ignore the new interface until the
3274 					 * next interval; as there's no easy way
3275 					 * to acquire statistics between time
3276 					 * of the plumb and the next interval
3277 					 * boundary.  This results in inaccurate
3278 					 * total values for current interval.
3279 					 *
3280 					 * Note the case when an interface is
3281 					 * unplumbed; as similar problems exist.
3282 					 * The unplumbed interface is not in the
3283 					 * current list, and there's no easy way
3284 					 * to account for the statistics between
3285 					 * the previous interval and time of the
3286 					 * unplumb.  Therefore, we (in a sense)
3287 					 * ignore the removed interface by only
3288 					 * involving "current" interfaces when
3289 					 * computing the total statistics.
3290 					 * Unfortunately, this also results in
3291 					 * inaccurate values for interval total.
3292 					 */
3293 
3294 					for (walkold = oldlist;
3295 					    walkold != NULL;
3296 					    walkold = walkold->next_if) {
3297 						if (strcmp(walkold->ifname,
3298 						    buf) == 0) {
3299 							if_stat_total(
3300 							    &walkold->tot,
3301 							    &t, &sum);
3302 							break;
3303 						}
3304 					}
3305 
3306 				}
3307 
3308 				*nextnew = NULL;
3309 
3310 				(void) printf("%-7llu %-5llu %-7llu "
3311 				    "%-5llu %-6llu ",
3312 				    new.ipackets - old.ipackets,
3313 				    new.ierrors - old.ierrors,
3314 				    new.opackets - old.opackets,
3315 				    new.oerrors - old.oerrors,
3316 				    new.collisions - old.collisions);
3317 
3318 				(void) printf("%-7llu %-5llu %-7llu "
3319 				    "%-5llu %-6llu\n", sum.ipackets,
3320 				    sum.ierrors, sum.opackets,
3321 				    sum.oerrors, sum.collisions);
3322 
3323 				/*
3324 				 * Tidy things up once finished.
3325 				 */
3326 
3327 				old = new;
3328 				cleanlist = oldlist;
3329 				oldlist = newlist;
3330 				while (cleanlist != NULL) {
3331 					tlp = cleanlist->next_if;
3332 					free(cleanlist);
3333 					cleanlist = tlp;
3334 				}
3335 			}
3336 			break;
3337 		}
3338 		case MIB2_IP6:
3339 		if (item->mib_id != MIB2_IP6_ADDR ||
3340 		    !family_selected(AF_INET6))
3341 			continue;
3342 		{
3343 			static struct ifstat	old6 = {0L, 0L, 0L, 0L, 0L};
3344 			static struct ifstat	new6 = {0L, 0L, 0L, 0L, 0L};
3345 			struct ifstat		sum6;
3346 			struct iflist		*newlist6 = NULL;
3347 			static struct iflist	*oldlist6 = NULL;
3348 			kstat_t	 *ksp;
3349 
3350 			if (once_only) {
3351 				char    ifname[LIFNAMSIZ + 1];
3352 				char    logintname[LIFNAMSIZ + 1];
3353 				mib2_ipv6AddrEntry_t *ap6;
3354 				struct ifstat	stat = {0L, 0L, 0L, 0L, 0L};
3355 				boolean_t	first = B_TRUE;
3356 				uint32_t	new_ifindex;
3357 
3358 				if (Xflag)
3359 					(void) printf("if_report: %d items\n",
3360 					    (item->length)
3361 					    / sizeof (mib2_ipv6AddrEntry_t));
3362 				for (ap6 = (mib2_ipv6AddrEntry_t *)item->valp;
3363 				    (char *)ap6 < (char *)item->valp
3364 				    + item->length;
3365 				    ap6++) {
3366 					(void) octetstr(&ap6->ipv6AddrIfIndex,
3367 					    'a', logintname,
3368 					    sizeof (logintname));
3369 					(void) strcpy(ifname, logintname);
3370 					(void) strtok(ifname, ":");
3371 					if (matchname != NULL &&
3372 					    strcmp(matchname, ifname) != 0 &&
3373 					    strcmp(matchname, logintname) != 0)
3374 						continue;
3375 					new_ifindex =
3376 					    if_nametoindex(logintname);
3377 
3378 					/*
3379 					 * First lookup the "link" kstats in
3380 					 * case the link is renamed. Then
3381 					 * fallback to the legacy kstats for
3382 					 * those non-GLDv3 links.
3383 					 */
3384 					if (new_ifindex != ifindex_v6 &&
3385 					    ((ksp = kstat_lookup(kc, "link", 0,
3386 					    ifname)) != NULL ||
3387 					    (ksp = kstat_lookup(kc, NULL, -1,
3388 					    ifname)) != NULL)) {
3389 						(void) safe_kstat_read(kc, ksp,
3390 						    NULL);
3391 						stat.ipackets =
3392 						    kstat_named_value(ksp,
3393 						    "ipackets");
3394 						stat.ierrors =
3395 						    kstat_named_value(ksp,
3396 						    "ierrors");
3397 						stat.opackets =
3398 						    kstat_named_value(ksp,
3399 						    "opackets");
3400 						stat.oerrors =
3401 						    kstat_named_value(ksp,
3402 						    "oerrors");
3403 						stat.collisions =
3404 						    kstat_named_value(ksp,
3405 						    "collisions");
3406 						if (first) {
3407 							if (!first_header)
3408 								(void) putchar(
3409 								    '\n');
3410 							first_header = B_FALSE;
3411 							(void) printf(
3412 							    "%-5.5s %-5.5s%"
3413 							    "-27.27s %-27.27s "
3414 							    "%-6.6s %-5.5s "
3415 							    "%-6.6s %-5.5s "
3416 							    "%-6.6s\n",
3417 							    "Name", "Mtu",
3418 							    "Net/Dest",
3419 							    "Address", "Ipkts",
3420 							    "Ierrs", "Opkts",
3421 							    "Oerrs", "Collis");
3422 							first = B_FALSE;
3423 						}
3424 						if_report_ip6(ap6, ifname,
3425 						    logintname, &stat, B_TRUE);
3426 						ifindex_v6 = new_ifindex;
3427 					} else {
3428 						if_report_ip6(ap6, ifname,
3429 						    logintname, &stat, B_FALSE);
3430 					}
3431 				}
3432 			} else if (!alreadydone) {
3433 				char    ifname[LIFNAMSIZ + 1];
3434 				char    buf[IFNAMSIZ + 1];
3435 				mib2_ipv6AddrEntry_t *ap6;
3436 				struct ifstat   t;
3437 				struct iflist	*tlp = NULL;
3438 				struct iflist	**nextnew = &newlist6;
3439 				struct iflist	*walkold;
3440 				struct iflist	*cleanlist;
3441 				boolean_t	found_if = B_FALSE;
3442 
3443 				alreadydone = B_TRUE; /* ignore other case */
3444 
3445 				/*
3446 				 * Check if there is anything to do.
3447 				 */
3448 				if (item->length <
3449 				    sizeof (mib2_ipv6AddrEntry_t)) {
3450 					fail(0, "No compatible interfaces");
3451 				}
3452 
3453 				/*
3454 				 * Find the "right" entry:
3455 				 * If an interface name to match has been
3456 				 * supplied then try and find it, otherwise
3457 				 * match the first non-loopback interface found.
3458 				 * Use lo0 if all else fails.
3459 				 */
3460 				for (ap6 = (mib2_ipv6AddrEntry_t *)item->valp;
3461 				    (char *)ap6 < (char *)item->valp
3462 				    + item->length;
3463 				    ap6++) {
3464 					(void) octetstr(&ap6->ipv6AddrIfIndex,
3465 					    'a', ifname, sizeof (ifname));
3466 					(void) strtok(ifname, ":");
3467 
3468 					if (matchname) {
3469 						if (strcmp(matchname,
3470 						    ifname) == 0) {
3471 							found_if = B_TRUE;
3472 							break;
3473 						}
3474 					} else if (strcmp(ifname, "lo0") != 0)
3475 						break;
3476 				}
3477 
3478 				if (matchname == NULL) {
3479 					matchname = ifname;
3480 				} else {
3481 					if (!found_if)
3482 						fail(0, "-I: %s no such "
3483 						    "interface.", matchname);
3484 				}
3485 
3486 				if (Iflag_only == 0 || !reentry) {
3487 					(void) printf(
3488 					    "    input   %-6.6s"
3489 					    "    output	",
3490 					    matchname);
3491 					(void) printf("   input  (Total)"
3492 					    "    output\n");
3493 					(void) printf("%-7.7s %-5.5s %-7.7s "
3494 					    "%-5.5s %-6.6s ",
3495 					    "packets", "errs", "packets",
3496 					    "errs", "colls");
3497 					(void) printf("%-7.7s %-5.5s %-7.7s "
3498 					    "%-5.5s %-6.6s\n",
3499 					    "packets", "errs", "packets",
3500 					    "errs", "colls");
3501 				}
3502 
3503 				sum6 = zerostat;
3504 
3505 				for (ap6 = (mib2_ipv6AddrEntry_t *)item->valp;
3506 				    (char *)ap6 < (char *)item->valp
3507 				    + item->length;
3508 				    ap6++) {
3509 					(void) octetstr(&ap6->ipv6AddrIfIndex,
3510 					    'a', buf, sizeof (buf));
3511 					(void) strtok(buf, ":");
3512 
3513 					/*
3514 					 * We have reduced the IP interface
3515 					 * name, which could have been a
3516 					 * logical, down to a name suitable
3517 					 * for use with kstats.
3518 					 * We treat this name as unique and
3519 					 * only collate statistics for it once
3520 					 * per pass. This is to avoid falsely
3521 					 * amplifying these statistics by the
3522 					 * the number of logical instances.
3523 					 */
3524 
3525 					if ((tlp != NULL) &&
3526 					    ((strcmp(buf, tlp->ifname) == 0))) {
3527 						continue;
3528 					}
3529 
3530 					/*
3531 					 * First lookup the "link" kstats in
3532 					 * case the link is renamed. Then
3533 					 * fallback to the legacy kstats for
3534 					 * those non-GLDv3 links.
3535 					 */
3536 					if (((ksp = kstat_lookup(kc, "link",
3537 					    0, buf)) != NULL ||
3538 					    (ksp = kstat_lookup(kc, NULL, -1,
3539 					    buf)) != NULL) && (ksp->ks_type ==
3540 					    KSTAT_TYPE_NAMED)) {
3541 						(void) safe_kstat_read(kc,
3542 						    ksp, NULL);
3543 					}
3544 
3545 					t.ipackets = kstat_named_value(ksp,
3546 					    "ipackets");
3547 					t.ierrors = kstat_named_value(ksp,
3548 					    "ierrors");
3549 					t.opackets = kstat_named_value(ksp,
3550 					    "opackets");
3551 					t.oerrors = kstat_named_value(ksp,
3552 					    "oerrors");
3553 					t.collisions = kstat_named_value(ksp,
3554 					    "collisions");
3555 
3556 					if (strcmp(buf, matchname) == 0)
3557 						new6 = t;
3558 
3559 					/* Build the interface list */
3560 
3561 					tlp = malloc(sizeof (struct iflist));
3562 					(void) strlcpy(tlp->ifname, buf,
3563 					    sizeof (tlp->ifname));
3564 					tlp->tot = t;
3565 					*nextnew = tlp;
3566 					nextnew = &tlp->next_if;
3567 
3568 					/*
3569 					 * First time through.
3570 					 * Just add up the interface stats.
3571 					 */
3572 
3573 					if (oldlist6 == NULL) {
3574 						if_stat_total(&zerostat,
3575 						    &t, &sum6);
3576 						continue;
3577 					}
3578 
3579 					/*
3580 					 * Walk old list for the interface.
3581 					 *
3582 					 * If found, add difference to total.
3583 					 *
3584 					 * If not, an interface has been plumbed
3585 					 * up.  In this case, we will simply
3586 					 * ignore the new interface until the
3587 					 * next interval; as there's no easy way
3588 					 * to acquire statistics between time
3589 					 * of the plumb and the next interval
3590 					 * boundary.  This results in inaccurate
3591 					 * total values for current interval.
3592 					 *
3593 					 * Note the case when an interface is
3594 					 * unplumbed; as similar problems exist.
3595 					 * The unplumbed interface is not in the
3596 					 * current list, and there's no easy way
3597 					 * to account for the statistics between
3598 					 * the previous interval and time of the
3599 					 * unplumb.  Therefore, we (in a sense)
3600 					 * ignore the removed interface by only
3601 					 * involving "current" interfaces when
3602 					 * computing the total statistics.
3603 					 * Unfortunately, this also results in
3604 					 * inaccurate values for interval total.
3605 					 */
3606 
3607 					for (walkold = oldlist6;
3608 					    walkold != NULL;
3609 					    walkold = walkold->next_if) {
3610 						if (strcmp(walkold->ifname,
3611 						    buf) == 0) {
3612 							if_stat_total(
3613 							    &walkold->tot,
3614 							    &t, &sum6);
3615 							break;
3616 						}
3617 					}
3618 
3619 				}
3620 
3621 				*nextnew = NULL;
3622 
3623 				(void) printf("%-7llu %-5llu %-7llu "
3624 				    "%-5llu %-6llu ",
3625 				    new6.ipackets - old6.ipackets,
3626 				    new6.ierrors - old6.ierrors,
3627 				    new6.opackets - old6.opackets,
3628 				    new6.oerrors - old6.oerrors,
3629 				    new6.collisions - old6.collisions);
3630 
3631 				(void) printf("%-7llu %-5llu %-7llu "
3632 				    "%-5llu %-6llu\n", sum6.ipackets,
3633 				    sum6.ierrors, sum6.opackets,
3634 				    sum6.oerrors, sum6.collisions);
3635 
3636 				/*
3637 				 * Tidy things up once finished.
3638 				 */
3639 
3640 				old6 = new6;
3641 				cleanlist = oldlist6;
3642 				oldlist6 = newlist6;
3643 				while (cleanlist != NULL) {
3644 					tlp = cleanlist->next_if;
3645 					free(cleanlist);
3646 					cleanlist = tlp;
3647 				}
3648 			}
3649 			break;
3650 		}
3651 		}
3652 		(void) fflush(stdout);
3653 	}
3654 	if ((Iflag_only == 0) && (!once_only))
3655 		(void) putchar('\n');
3656 	reentry = B_TRUE;
3657 }
3658 
3659 static void
3660 if_report_ip4(mib2_ipAddrEntry_t *ap,
3661     char ifname[], char logintname[], struct ifstat *statptr,
3662     boolean_t ksp_not_null)
3663 {
3664 
3665 	char abuf[MAXHOSTNAMELEN + 4];	/* Include /<num> for CIDR-printing. */
3666 	char dstbuf[MAXHOSTNAMELEN + 1];
3667 
3668 	if (ksp_not_null) {
3669 		(void) printf("%-5s %-4u ",
3670 		    ifname, ap->ipAdEntInfo.ae_mtu);
3671 		if (ap->ipAdEntInfo.ae_flags & IFF_POINTOPOINT)
3672 			(void) pr_addr(ap->ipAdEntInfo.ae_pp_dst_addr,
3673 			    abuf, sizeof (abuf));
3674 		else
3675 			(void) pr_netaddr(ap->ipAdEntAddr,
3676 			    ap->ipAdEntNetMask, abuf, sizeof (abuf));
3677 		(void) printf("%-13s %-14s %-6llu %-5llu %-6llu %-5llu "
3678 		    "%-6llu %-6llu\n",
3679 		    abuf, pr_addr(ap->ipAdEntAddr, dstbuf, sizeof (dstbuf)),
3680 		    statptr->ipackets, statptr->ierrors,
3681 		    statptr->opackets, statptr->oerrors,
3682 		    statptr->collisions, 0LL);
3683 	}
3684 	/*
3685 	 * Print logical interface info if Aflag set (including logical unit 0)
3686 	 */
3687 	if (Aflag) {
3688 		*statptr = zerostat;
3689 		statptr->ipackets = ap->ipAdEntInfo.ae_ibcnt;
3690 		statptr->opackets = ap->ipAdEntInfo.ae_obcnt;
3691 
3692 		(void) printf("%-5s %-4u ", logintname, ap->ipAdEntInfo.ae_mtu);
3693 		if (ap->ipAdEntInfo.ae_flags & IFF_POINTOPOINT)
3694 			(void) pr_addr(ap->ipAdEntInfo.ae_pp_dst_addr, abuf,
3695 			    sizeof (abuf));
3696 		else
3697 			(void) pr_netaddr(ap->ipAdEntAddr, ap->ipAdEntNetMask,
3698 			    abuf, sizeof (abuf));
3699 
3700 		(void) printf("%-13s %-14s %-6llu %-5s %-6s "
3701 		    "%-5s %-6s %-6llu\n", abuf,
3702 		    pr_addr(ap->ipAdEntAddr, dstbuf, sizeof (dstbuf)),
3703 		    statptr->ipackets, "N/A", "N/A", "N/A", "N/A",
3704 		    0LL);
3705 	}
3706 }
3707 
3708 static void
3709 if_report_ip6(mib2_ipv6AddrEntry_t *ap6,
3710     char ifname[], char logintname[], struct ifstat *statptr,
3711     boolean_t ksp_not_null)
3712 {
3713 
3714 	char abuf[MAXHOSTNAMELEN + 1];
3715 	char dstbuf[MAXHOSTNAMELEN + 1];
3716 
3717 	if (ksp_not_null) {
3718 		(void) printf("%-5s %-4u ", ifname, ap6->ipv6AddrInfo.ae_mtu);
3719 		if (ap6->ipv6AddrInfo.ae_flags &
3720 		    IFF_POINTOPOINT) {
3721 			(void) pr_addr6(&ap6->ipv6AddrInfo.ae_pp_dst_addr,
3722 			    abuf, sizeof (abuf));
3723 		} else {
3724 			(void) pr_prefix6(&ap6->ipv6AddrAddress,
3725 			    ap6->ipv6AddrPfxLength, abuf,
3726 			    sizeof (abuf));
3727 		}
3728 		(void) printf("%-27s %-27s %-6llu %-5llu "
3729 		    "%-6llu %-5llu %-6llu\n",
3730 		    abuf, pr_addr6(&ap6->ipv6AddrAddress, dstbuf,
3731 		    sizeof (dstbuf)),
3732 		    statptr->ipackets, statptr->ierrors, statptr->opackets,
3733 		    statptr->oerrors, statptr->collisions);
3734 	}
3735 	/*
3736 	 * Print logical interface info if Aflag set (including logical unit 0)
3737 	 */
3738 	if (Aflag) {
3739 		*statptr = zerostat;
3740 		statptr->ipackets = ap6->ipv6AddrInfo.ae_ibcnt;
3741 		statptr->opackets = ap6->ipv6AddrInfo.ae_obcnt;
3742 
3743 		(void) printf("%-5s %-4u ", logintname,
3744 		    ap6->ipv6AddrInfo.ae_mtu);
3745 		if (ap6->ipv6AddrInfo.ae_flags & IFF_POINTOPOINT)
3746 			(void) pr_addr6(&ap6->ipv6AddrInfo.ae_pp_dst_addr,
3747 			    abuf, sizeof (abuf));
3748 		else
3749 			(void) pr_prefix6(&ap6->ipv6AddrAddress,
3750 			    ap6->ipv6AddrPfxLength, abuf, sizeof (abuf));
3751 		(void) printf("%-27s %-27s %-6llu %-5s %-6s %-5s %-6s\n",
3752 		    abuf, pr_addr6(&ap6->ipv6AddrAddress, dstbuf,
3753 		    sizeof (dstbuf)),
3754 		    statptr->ipackets, "N/A", "N/A", "N/A", "N/A");
3755 	}
3756 }
3757 
3758 /* --------------------- DHCP_REPORT  (netstat -D) ------------------------- */
3759 
3760 static boolean_t
3761 dhcp_do_ipc(dhcp_ipc_type_t type, const char *ifname, boolean_t printed_one)
3762 {
3763 	dhcp_ipc_request_t	*request;
3764 	dhcp_ipc_reply_t	*reply;
3765 	int			error;
3766 
3767 	request = dhcp_ipc_alloc_request(type, ifname, NULL, 0, DHCP_TYPE_NONE);
3768 	if (request == NULL)
3769 		fail(0, "dhcp_do_ipc: out of memory");
3770 
3771 	error = dhcp_ipc_make_request(request, &reply, DHCP_IPC_WAIT_DEFAULT);
3772 	if (error != 0) {
3773 		free(request);
3774 		fail(0, "dhcp_do_ipc: %s", dhcp_ipc_strerror(error));
3775 	}
3776 
3777 	free(request);
3778 	error = reply->return_code;
3779 	if (error == DHCP_IPC_E_UNKIF) {
3780 		free(reply);
3781 		return (printed_one);
3782 	}
3783 	if (error != 0) {
3784 		free(reply);
3785 		fail(0, "dhcp_do_ipc: %s", dhcp_ipc_strerror(error));
3786 	}
3787 
3788 	if (timestamp_fmt != NODATE)
3789 		print_timestamp(timestamp_fmt);
3790 
3791 	if (!printed_one)
3792 		(void) printf("%s", dhcp_status_hdr_string());
3793 
3794 	(void) printf("%s", dhcp_status_reply_to_string(reply));
3795 	free(reply);
3796 	return (B_TRUE);
3797 }
3798 
3799 /*
3800  * dhcp_walk_interfaces: walk the list of interfaces for a given address
3801  * family (af).  For each, print out the DHCP status using dhcp_do_ipc.
3802  */
3803 static boolean_t
3804 dhcp_walk_interfaces(int af, boolean_t printed_one)
3805 {
3806 	struct lifnum	lifn;
3807 	struct lifconf	lifc;
3808 	int		n_ifs, i, sock_fd;
3809 
3810 	sock_fd = socket(af, SOCK_DGRAM, 0);
3811 	if (sock_fd == -1)
3812 		return (printed_one);
3813 
3814 	/*
3815 	 * SIOCGLIFNUM is just an estimate.  If the ioctl fails, we don't care;
3816 	 * just drive on and use SIOCGLIFCONF with increasing buffer sizes, as
3817 	 * is traditional.
3818 	 */
3819 	(void) memset(&lifn, 0, sizeof (lifn));
3820 	lifn.lifn_family = af;
3821 	lifn.lifn_flags = LIFC_ALLZONES | LIFC_NOXMIT | LIFC_UNDER_IPMP;
3822 	if (ioctl(sock_fd, SIOCGLIFNUM, &lifn) == -1)
3823 		n_ifs = LIFN_GUARD_VALUE;
3824 	else
3825 		n_ifs = lifn.lifn_count + LIFN_GUARD_VALUE;
3826 
3827 	(void) memset(&lifc, 0, sizeof (lifc));
3828 	lifc.lifc_family = af;
3829 	lifc.lifc_flags = lifn.lifn_flags;
3830 	lifc.lifc_len = n_ifs * sizeof (struct lifreq);
3831 	lifc.lifc_buf = malloc(lifc.lifc_len);
3832 	if (lifc.lifc_buf != NULL) {
3833 
3834 		if (ioctl(sock_fd, SIOCGLIFCONF, &lifc) == -1) {
3835 			(void) close(sock_fd);
3836 			free(lifc.lifc_buf);
3837 			return (B_FALSE);
3838 		}
3839 
3840 		n_ifs = lifc.lifc_len / sizeof (struct lifreq);
3841 
3842 		for (i = 0; i < n_ifs; i++) {
3843 			printed_one = dhcp_do_ipc(DHCP_STATUS |
3844 			    (af == AF_INET6 ? DHCP_V6 : 0),
3845 			    lifc.lifc_req[i].lifr_name, printed_one);
3846 		}
3847 	}
3848 	(void) close(sock_fd);
3849 	free(lifc.lifc_buf);
3850 	return (printed_one);
3851 }
3852 
3853 static void
3854 dhcp_report(char *ifname)
3855 {
3856 	boolean_t printed_one;
3857 
3858 	if (!family_selected(AF_INET) && !family_selected(AF_INET6))
3859 		return;
3860 
3861 	printed_one = B_FALSE;
3862 	if (ifname != NULL) {
3863 		if (family_selected(AF_INET)) {
3864 			printed_one = dhcp_do_ipc(DHCP_STATUS, ifname,
3865 			    printed_one);
3866 		}
3867 		if (family_selected(AF_INET6)) {
3868 			printed_one = dhcp_do_ipc(DHCP_STATUS | DHCP_V6,
3869 			    ifname, printed_one);
3870 		}
3871 		if (!printed_one) {
3872 			fail(0, "%s: %s", ifname,
3873 			    dhcp_ipc_strerror(DHCP_IPC_E_UNKIF));
3874 		}
3875 	} else {
3876 		if (family_selected(AF_INET)) {
3877 			printed_one = dhcp_walk_interfaces(AF_INET,
3878 			    printed_one);
3879 		}
3880 		if (family_selected(AF_INET6))
3881 			(void) dhcp_walk_interfaces(AF_INET6, printed_one);
3882 	}
3883 }
3884 
3885 /* --------------------- GROUP_REPORT (netstat -g) ------------------------- */
3886 
3887 static void
3888 group_report(mib_item_t *item)
3889 {
3890 	mib_item_t	*v4grp = NULL, *v4src = NULL;
3891 	mib_item_t	*v6grp = NULL, *v6src = NULL;
3892 	int		jtemp = 0;
3893 	char		ifname[LIFNAMSIZ + 1];
3894 	char		abuf[MAXHOSTNAMELEN + 1];
3895 	ip_member_t	*ipmp;
3896 	ip_grpsrc_t	*ips;
3897 	ipv6_member_t	*ipmp6;
3898 	ipv6_grpsrc_t	*ips6;
3899 	boolean_t	first, first_src;
3900 
3901 	for (; item; item = item->next_item) {
3902 		if (Xflag) {
3903 			(void) printf("[%4d] Group = %d, mib_id = %d, "
3904 			    "length = %d, valp = 0x%p\n",
3905 			    jtemp++, item->group, item->mib_id, item->length,
3906 			    item->valp);
3907 		}
3908 		if (item->group == MIB2_IP && family_selected(AF_INET)) {
3909 			switch (item->mib_id) {
3910 			case EXPER_IP_GROUP_MEMBERSHIP:
3911 				v4grp = item;
3912 				if (Xflag)
3913 					(void) printf("item is v4grp info\n");
3914 				break;
3915 			case EXPER_IP_GROUP_SOURCES:
3916 				v4src = item;
3917 				if (Xflag)
3918 					(void) printf("item is v4src info\n");
3919 				break;
3920 			default:
3921 				continue;
3922 			}
3923 			continue;
3924 		}
3925 		if (item->group == MIB2_IP6 && family_selected(AF_INET6)) {
3926 			switch (item->mib_id) {
3927 			case EXPER_IP6_GROUP_MEMBERSHIP:
3928 				v6grp = item;
3929 				if (Xflag)
3930 					(void) printf("item is v6grp info\n");
3931 				break;
3932 			case EXPER_IP6_GROUP_SOURCES:
3933 				v6src = item;
3934 				if (Xflag)
3935 					(void) printf("item is v6src info\n");
3936 				break;
3937 			default:
3938 				continue;
3939 			}
3940 		}
3941 	}
3942 
3943 	if (family_selected(AF_INET) && v4grp != NULL) {
3944 		if (Xflag)
3945 			(void) printf("%u records for ipGroupMember:\n",
3946 			    v4grp->length / sizeof (ip_member_t));
3947 
3948 		first = B_TRUE;
3949 		for (ipmp = (ip_member_t *)v4grp->valp;
3950 		    (char *)ipmp < (char *)v4grp->valp + v4grp->length;
3951 		    ipmp = (ip_member_t *)((char *)ipmp + ipMemberEntrySize)) {
3952 			if (first) {
3953 				(void) puts(v4compat ?
3954 				    "Group Memberships" :
3955 				    "Group Memberships: IPv4");
3956 				(void) puts("Interface "
3957 				    "Group                RefCnt");
3958 				(void) puts("--------- "
3959 				    "-------------------- ------");
3960 				first = B_FALSE;
3961 			}
3962 
3963 			(void) printf("%-9s %-20s %6u\n",
3964 			    octetstr(&ipmp->ipGroupMemberIfIndex, 'a',
3965 			    ifname, sizeof (ifname)),
3966 			    pr_addr(ipmp->ipGroupMemberAddress,
3967 			    abuf, sizeof (abuf)),
3968 			    ipmp->ipGroupMemberRefCnt);
3969 
3970 			if (!Vflag || v4src == NULL)
3971 				continue;
3972 
3973 			if (Xflag)
3974 				(void) printf("scanning %u ipGroupSource "
3975 				    "records...\n",
3976 				    v4src->length/sizeof (ip_grpsrc_t));
3977 
3978 			first_src = B_TRUE;
3979 			for (ips = (ip_grpsrc_t *)v4src->valp;
3980 			    (char *)ips < (char *)v4src->valp + v4src->length;
3981 			    ips = (ip_grpsrc_t *)((char *)ips +
3982 			    ipGroupSourceEntrySize)) {
3983 				/*
3984 				 * We assume that all source addrs for a given
3985 				 * interface/group pair are contiguous, so on
3986 				 * the first non-match after we've found at
3987 				 * least one, we bail.
3988 				 */
3989 				if ((ipmp->ipGroupMemberAddress !=
3990 				    ips->ipGroupSourceGroup) ||
3991 				    (!octetstrmatch(&ipmp->ipGroupMemberIfIndex,
3992 				    &ips->ipGroupSourceIfIndex))) {
3993 					if (first_src)
3994 						continue;
3995 					else
3996 						break;
3997 				}
3998 				if (first_src) {
3999 					(void) printf("\t%s:    %s\n",
4000 					    fmodestr(
4001 					    ipmp->ipGroupMemberFilterMode),
4002 					    pr_addr(ips->ipGroupSourceAddress,
4003 					    abuf, sizeof (abuf)));
4004 					first_src = B_FALSE;
4005 					continue;
4006 				}
4007 
4008 				(void) printf("\t            %s\n",
4009 				    pr_addr(ips->ipGroupSourceAddress, abuf,
4010 				    sizeof (abuf)));
4011 			}
4012 		}
4013 		(void) putchar('\n');
4014 	}
4015 
4016 	if (family_selected(AF_INET6) && v6grp != NULL) {
4017 		if (Xflag)
4018 			(void) printf("%u records for ipv6GroupMember:\n",
4019 			    v6grp->length / sizeof (ipv6_member_t));
4020 
4021 		first = B_TRUE;
4022 		for (ipmp6 = (ipv6_member_t *)v6grp->valp;
4023 		    (char *)ipmp6 < (char *)v6grp->valp + v6grp->length;
4024 		    ipmp6 = (ipv6_member_t *)((char *)ipmp6 +
4025 		    ipv6MemberEntrySize)) {
4026 			if (first) {
4027 				(void) puts("Group Memberships: "
4028 				    "IPv6");
4029 				(void) puts(" If       "
4030 				    "Group                   RefCnt");
4031 				(void) puts("----- "
4032 				    "--------------------------- ------");
4033 				first = B_FALSE;
4034 			}
4035 
4036 			(void) printf("%-5s %-27s %5u\n",
4037 			    ifindex2str(ipmp6->ipv6GroupMemberIfIndex, ifname),
4038 			    pr_addr6(&ipmp6->ipv6GroupMemberAddress,
4039 			    abuf, sizeof (abuf)),
4040 			    ipmp6->ipv6GroupMemberRefCnt);
4041 
4042 			if (!Vflag || v6src == NULL)
4043 				continue;
4044 
4045 			if (Xflag)
4046 				(void) printf("scanning %u ipv6GroupSource "
4047 				    "records...\n",
4048 				    v6src->length/sizeof (ipv6_grpsrc_t));
4049 
4050 			first_src = B_TRUE;
4051 			for (ips6 = (ipv6_grpsrc_t *)v6src->valp;
4052 			    (char *)ips6 < (char *)v6src->valp + v6src->length;
4053 			    ips6 = (ipv6_grpsrc_t *)((char *)ips6 +
4054 			    ipv6GroupSourceEntrySize)) {
4055 				/* same assumption as in the v4 case above */
4056 				if ((ipmp6->ipv6GroupMemberIfIndex !=
4057 				    ips6->ipv6GroupSourceIfIndex) ||
4058 				    (!IN6_ARE_ADDR_EQUAL(
4059 				    &ipmp6->ipv6GroupMemberAddress,
4060 				    &ips6->ipv6GroupSourceGroup))) {
4061 					if (first_src)
4062 						continue;
4063 					else
4064 						break;
4065 				}
4066 				if (first_src) {
4067 					(void) printf("\t%s:    %s\n",
4068 					    fmodestr(
4069 					    ipmp6->ipv6GroupMemberFilterMode),
4070 					    pr_addr6(
4071 					    &ips6->ipv6GroupSourceAddress,
4072 					    abuf, sizeof (abuf)));
4073 					first_src = B_FALSE;
4074 					continue;
4075 				}
4076 
4077 				(void) printf("\t            %s\n",
4078 				    pr_addr6(&ips6->ipv6GroupSourceAddress,
4079 				    abuf, sizeof (abuf)));
4080 			}
4081 		}
4082 		(void) putchar('\n');
4083 	}
4084 
4085 	(void) putchar('\n');
4086 	(void) fflush(stdout);
4087 }
4088 
4089 /* --------------------- DCE_REPORT (netstat -d) ------------------------- */
4090 
4091 #define	FLBUFSIZE	8
4092 
4093 /* Assumes flbuf is at least 5 characters; callers use FLBUFSIZE */
4094 static char *
4095 dceflags2str(uint32_t flags, char *flbuf)
4096 {
4097 	char *str = flbuf;
4098 
4099 	if (flags & DCEF_DEFAULT)
4100 		*str++ = 'D';
4101 	if (flags & DCEF_PMTU)
4102 		*str++ = 'P';
4103 	if (flags & DCEF_UINFO)
4104 		*str++ = 'U';
4105 	if (flags & DCEF_TOO_SMALL_PMTU)
4106 		*str++ = 'S';
4107 	*str++ = '\0';
4108 	return (flbuf);
4109 }
4110 
4111 static void
4112 dce_report(mib_item_t *item)
4113 {
4114 	mib_item_t	*v4dce = NULL;
4115 	mib_item_t	*v6dce = NULL;
4116 	int		jtemp = 0;
4117 	char		ifname[LIFNAMSIZ + 1];
4118 	char		abuf[MAXHOSTNAMELEN + 1];
4119 	char		flbuf[FLBUFSIZE];
4120 	boolean_t	first;
4121 	dest_cache_entry_t *dce;
4122 
4123 	for (; item; item = item->next_item) {
4124 		if (Xflag) {
4125 			(void) printf("[%4d] Group = %d, mib_id = %d, "
4126 			    "length = %d, valp = 0x%p\n", jtemp++,
4127 			    item->group, item->mib_id, item->length,
4128 			    item->valp);
4129 		}
4130 		if (item->group == MIB2_IP && family_selected(AF_INET) &&
4131 		    item->mib_id == EXPER_IP_DCE) {
4132 			v4dce = item;
4133 			if (Xflag)
4134 				(void) printf("item is v4dce info\n");
4135 		}
4136 		if (item->group == MIB2_IP6 && family_selected(AF_INET6) &&
4137 		    item->mib_id == EXPER_IP_DCE) {
4138 			v6dce = item;
4139 			if (Xflag)
4140 				(void) printf("item is v6dce info\n");
4141 		}
4142 	}
4143 
4144 	if (family_selected(AF_INET) && v4dce != NULL) {
4145 		if (Xflag)
4146 			(void) printf("%u records for DestCacheEntry:\n",
4147 			    v4dce->length / ipDestEntrySize);
4148 
4149 		first = B_TRUE;
4150 		for (dce = (dest_cache_entry_t *)v4dce->valp;
4151 		    (char *)dce < (char *)v4dce->valp + v4dce->length;
4152 		    dce = (dest_cache_entry_t *)((char *)dce +
4153 		    ipDestEntrySize)) {
4154 			if (first) {
4155 				(void) putchar('\n');
4156 				(void) puts("Destination Cache Entries: IPv4");
4157 				(void) puts(
4158 				    "Address               PMTU   Age  Flags");
4159 				(void) puts(
4160 				    "-------------------- ------ ----- -----");
4161 				first = B_FALSE;
4162 			}
4163 
4164 			(void) printf("%-20s %6u %5u %-5s\n",
4165 			    pr_addr(dce->DestIpv4Address, abuf, sizeof (abuf)),
4166 			    dce->DestPmtu, dce->DestAge,
4167 			    dceflags2str(dce->DestFlags, flbuf));
4168 		}
4169 	}
4170 
4171 	if (family_selected(AF_INET6) && v6dce != NULL) {
4172 		if (Xflag)
4173 			(void) printf("%u records for DestCacheEntry:\n",
4174 			    v6dce->length / ipDestEntrySize);
4175 
4176 		first = B_TRUE;
4177 		for (dce = (dest_cache_entry_t *)v6dce->valp;
4178 		    (char *)dce < (char *)v6dce->valp + v6dce->length;
4179 		    dce = (dest_cache_entry_t *)((char *)dce +
4180 		    ipDestEntrySize)) {
4181 			if (first) {
4182 				(void) putchar('\n');
4183 				(void) puts("Destination Cache Entries: IPv6");
4184 				(void) puts(
4185 				    "Address                      PMTU  "
4186 				    " Age Flags If ");
4187 				(void) puts(
4188 				    "--------------------------- ------ "
4189 				    "----- ----- ---");
4190 				first = B_FALSE;
4191 			}
4192 
4193 			(void) printf("%-27s %6u %5u %-5s %s\n",
4194 			    pr_addr6(&dce->DestIpv6Address, abuf,
4195 			    sizeof (abuf)),
4196 			    dce->DestPmtu, dce->DestAge,
4197 			    dceflags2str(dce->DestFlags, flbuf),
4198 			    dce->DestIfindex == 0 ? "" :
4199 			    ifindex2str(dce->DestIfindex, ifname));
4200 		}
4201 	}
4202 	(void) fflush(stdout);
4203 }
4204 
4205 /* --------------------- ARP_REPORT (netstat -p) -------------------------- */
4206 
4207 static void
4208 arp_report(mib_item_t *item)
4209 {
4210 	int		jtemp = 0;
4211 	char		ifname[LIFNAMSIZ + 1];
4212 	char		abuf[MAXHOSTNAMELEN + 1];
4213 	char		maskbuf[STR_EXPAND * OCTET_LENGTH + 1];
4214 	char		flbuf[32];	/* ACE_F_ flags */
4215 	char		xbuf[STR_EXPAND * OCTET_LENGTH + 1];
4216 	mib2_ipNetToMediaEntry_t	*np;
4217 	int		flags;
4218 	boolean_t	first;
4219 
4220 	if (!(family_selected(AF_INET)))
4221 		return;
4222 
4223 	for (; item; item = item->next_item) {
4224 		if (Xflag) {
4225 			(void) printf("[%4d] Group = %d, mib_id = %d, "
4226 			    "length = %d, valp = 0x%p\n", jtemp++,
4227 			    item->group, item->mib_id, item->length,
4228 			    item->valp);
4229 		}
4230 		if (!(item->group == MIB2_IP && item->mib_id == MIB2_IP_MEDIA))
4231 			continue;
4232 
4233 		if (Xflag)
4234 			(void) printf("%u records for "
4235 			    "ipNetToMediaEntryTable:\n",
4236 			    item->length/sizeof (mib2_ipNetToMediaEntry_t));
4237 
4238 		first = B_TRUE;
4239 		for (np = (mib2_ipNetToMediaEntry_t *)item->valp;
4240 		    (char *)np < (char *)item->valp + item->length;
4241 		    np = (mib2_ipNetToMediaEntry_t *)((char *)np +
4242 		    ipNetToMediaEntrySize)) {
4243 			if (first) {
4244 				(void) puts(v4compat ?
4245 				    "Net to Media Table" :
4246 				    "Net to Media Table: IPv4");
4247 				(void) puts("Device "
4248 				    "  IP Address               Mask      "
4249 				    "Flags      Phys Addr");
4250 				(void) puts("------ "
4251 				    "-------------------- --------------- "
4252 				    "-------- ---------------");
4253 				first = B_FALSE;
4254 			}
4255 
4256 			flbuf[0] = '\0';
4257 			flags = np->ipNetToMediaInfo.ntm_flags;
4258 			/*
4259 			 * Note that not all flags are possible at the same
4260 			 * time.  Patterns: SPLAy DUo
4261 			 */
4262 			if (flags & ACE_F_PERMANENT)
4263 				(void) strcat(flbuf, "S");
4264 			if (flags & ACE_F_PUBLISH)
4265 				(void) strcat(flbuf, "P");
4266 			if (flags & ACE_F_DYING)
4267 				(void) strcat(flbuf, "D");
4268 			if (!(flags & ACE_F_RESOLVED))
4269 				(void) strcat(flbuf, "U");
4270 			if (flags & ACE_F_MAPPING)
4271 				(void) strcat(flbuf, "M");
4272 			if (flags & ACE_F_MYADDR)
4273 				(void) strcat(flbuf, "L");
4274 			if (flags & ACE_F_UNVERIFIED)
4275 				(void) strcat(flbuf, "d");
4276 			if (flags & ACE_F_AUTHORITY)
4277 				(void) strcat(flbuf, "A");
4278 			if (flags & ACE_F_OLD)
4279 				(void) strcat(flbuf, "o");
4280 			if (flags & ACE_F_DELAYED)
4281 				(void) strcat(flbuf, "y");
4282 			(void) printf("%-6s %-20s %-15s %-8s %s\n",
4283 			    octetstr(&np->ipNetToMediaIfIndex, 'a',
4284 			    ifname, sizeof (ifname)),
4285 			    pr_addr(np->ipNetToMediaNetAddress,
4286 			    abuf, sizeof (abuf)),
4287 			    octetstr(&np->ipNetToMediaInfo.ntm_mask, 'd',
4288 			    maskbuf, sizeof (maskbuf)),
4289 			    flbuf,
4290 			    octetstr(&np->ipNetToMediaPhysAddress, 'h',
4291 			    xbuf, sizeof (xbuf)));
4292 		}
4293 	}
4294 	(void) fflush(stdout);
4295 }
4296 
4297 /* --------------------- NDP_REPORT (netstat -p) -------------------------- */
4298 
4299 static void
4300 ndp_report(mib_item_t *item)
4301 {
4302 	int		jtemp = 0;
4303 	char		abuf[MAXHOSTNAMELEN + 1];
4304 	char		*state;
4305 	char		*type;
4306 	char		xbuf[STR_EXPAND * OCTET_LENGTH + 1];
4307 	mib2_ipv6NetToMediaEntry_t	*np6;
4308 	char		ifname[LIFNAMSIZ + 1];
4309 	boolean_t	first;
4310 
4311 	if (!(family_selected(AF_INET6)))
4312 		return;
4313 
4314 	for (; item; item = item->next_item) {
4315 		if (Xflag) {
4316 			(void) printf("\n--- Entry %d ---\n", ++jtemp);
4317 			(void) printf("Group = %d, mib_id = %d, "
4318 			    "length = %d, valp = 0x%p\n",
4319 			    item->group, item->mib_id, item->length,
4320 			    item->valp);
4321 		}
4322 		if (!(item->group == MIB2_IP6 &&
4323 		    item->mib_id == MIB2_IP6_MEDIA))
4324 			continue;
4325 
4326 		first = B_TRUE;
4327 		for (np6 = (mib2_ipv6NetToMediaEntry_t *)item->valp;
4328 		    (char *)np6 < (char *)item->valp + item->length;
4329 		    np6 = (mib2_ipv6NetToMediaEntry_t *)((char *)np6 +
4330 		    ipv6NetToMediaEntrySize)) {
4331 			if (first) {
4332 				(void) puts("\nNet to Media Table: IPv6");
4333 				(void) puts(" If   Physical Address   "
4334 				    " Type      State      Destination/Mask");
4335 				(void) puts("----- -----------------  "
4336 				    "------- ------------ "
4337 				    "---------------------------");
4338 				first = B_FALSE;
4339 			}
4340 
4341 			switch (np6->ipv6NetToMediaState) {
4342 			case ND_INCOMPLETE:
4343 				state = "INCOMPLETE";
4344 				break;
4345 			case ND_REACHABLE:
4346 				state = "REACHABLE";
4347 				break;
4348 			case ND_STALE:
4349 				state = "STALE";
4350 				break;
4351 			case ND_DELAY:
4352 				state = "DELAY";
4353 				break;
4354 			case ND_PROBE:
4355 				state = "PROBE";
4356 				break;
4357 			case ND_UNREACHABLE:
4358 				state = "UNREACHABLE";
4359 				break;
4360 			default:
4361 				state = "UNKNOWN";
4362 			}
4363 
4364 			switch (np6->ipv6NetToMediaType) {
4365 			case 1:
4366 				type = "other";
4367 				break;
4368 			case 2:
4369 				type = "dynamic";
4370 				break;
4371 			case 3:
4372 				type = "static";
4373 				break;
4374 			case 4:
4375 				type = "local";
4376 				break;
4377 			default:
4378 				type = "UNKNOWN";
4379 			}
4380 			(void) printf("%-5s %-17s  %-7s %-12s %-27s\n",
4381 			    ifindex2str(np6->ipv6NetToMediaIfIndex, ifname),
4382 			    octetstr(&np6->ipv6NetToMediaPhysAddress, 'h',
4383 			    xbuf, sizeof (xbuf)),
4384 			    type,
4385 			    state,
4386 			    pr_addr6(&np6->ipv6NetToMediaNetAddress,
4387 			    abuf, sizeof (abuf)));
4388 		}
4389 	}
4390 	(void) putchar('\n');
4391 	(void) fflush(stdout);
4392 }
4393 
4394 /* ------------------------- ire_report (netstat -r) ------------------------ */
4395 
4396 typedef struct sec_attr_list_s {
4397 	struct sec_attr_list_s *sal_next;
4398 	const mib2_ipAttributeEntry_t *sal_attr;
4399 } sec_attr_list_t;
4400 
4401 static boolean_t ire_report_item_v4(const mib2_ipRouteEntry_t *, boolean_t,
4402     const sec_attr_list_t *);
4403 static boolean_t ire_report_item_v6(const mib2_ipv6RouteEntry_t *, boolean_t,
4404     const sec_attr_list_t *);
4405 static const char *pr_secattr(const sec_attr_list_t *);
4406 
4407 static void
4408 ire_report(const mib_item_t *item)
4409 {
4410 	int			jtemp = 0;
4411 	boolean_t		print_hdr_once_v4 = B_TRUE;
4412 	boolean_t		print_hdr_once_v6 = B_TRUE;
4413 	mib2_ipRouteEntry_t	*rp;
4414 	mib2_ipv6RouteEntry_t	*rp6;
4415 	sec_attr_list_t		**v4_attrs, **v4a;
4416 	sec_attr_list_t		**v6_attrs, **v6a;
4417 	sec_attr_list_t		*all_attrs, *aptr;
4418 	const mib_item_t	*iptr;
4419 	int			ipv4_route_count, ipv6_route_count;
4420 	int			route_attrs_count;
4421 
4422 	/*
4423 	 * Preparation pass: the kernel returns separate entries for IP routing
4424 	 * table entries and security attributes.  We loop through the
4425 	 * attributes first and link them into lists.
4426 	 */
4427 	ipv4_route_count = ipv6_route_count = route_attrs_count = 0;
4428 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
4429 		if (iptr->group == MIB2_IP6 && iptr->mib_id == MIB2_IP6_ROUTE)
4430 			ipv6_route_count += iptr->length / ipv6RouteEntrySize;
4431 		if (iptr->group == MIB2_IP && iptr->mib_id == MIB2_IP_ROUTE)
4432 			ipv4_route_count += iptr->length / ipRouteEntrySize;
4433 		if ((iptr->group == MIB2_IP || iptr->group == MIB2_IP6) &&
4434 		    iptr->mib_id == EXPER_IP_RTATTR)
4435 			route_attrs_count += iptr->length /
4436 			    ipRouteAttributeSize;
4437 	}
4438 	v4_attrs = v6_attrs = NULL;
4439 	all_attrs = NULL;
4440 	if (family_selected(AF_INET) && ipv4_route_count > 0) {
4441 		v4_attrs = calloc(ipv4_route_count, sizeof (*v4_attrs));
4442 		if (v4_attrs == NULL) {
4443 			perror("ire_report calloc v4_attrs failed");
4444 			return;
4445 		}
4446 	}
4447 	if (family_selected(AF_INET6) && ipv6_route_count > 0) {
4448 		v6_attrs = calloc(ipv6_route_count, sizeof (*v6_attrs));
4449 		if (v6_attrs == NULL) {
4450 			perror("ire_report calloc v6_attrs failed");
4451 			goto ire_report_done;
4452 		}
4453 	}
4454 	if (route_attrs_count > 0) {
4455 		all_attrs = malloc(route_attrs_count * sizeof (*all_attrs));
4456 		if (all_attrs == NULL) {
4457 			perror("ire_report malloc all_attrs failed");
4458 			goto ire_report_done;
4459 		}
4460 	}
4461 	aptr = all_attrs;
4462 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
4463 		mib2_ipAttributeEntry_t *iae;
4464 		sec_attr_list_t **alp;
4465 
4466 		if (v4_attrs != NULL && iptr->group == MIB2_IP &&
4467 		    iptr->mib_id == EXPER_IP_RTATTR) {
4468 			alp = v4_attrs;
4469 		} else if (v6_attrs != NULL && iptr->group == MIB2_IP6 &&
4470 		    iptr->mib_id == EXPER_IP_RTATTR) {
4471 			alp = v6_attrs;
4472 		} else {
4473 			continue;
4474 		}
4475 		for (iae = iptr->valp;
4476 		    (char *)iae < (char *)iptr->valp + iptr->length;
4477 		    iae = (mib2_ipAttributeEntry_t *)((char *)iae +
4478 		    ipRouteAttributeSize)) {
4479 			aptr->sal_next = alp[iae->iae_routeidx];
4480 			aptr->sal_attr = iae;
4481 			alp[iae->iae_routeidx] = aptr++;
4482 		}
4483 	}
4484 
4485 	v4a = v4_attrs;
4486 	v6a = v6_attrs;
4487 	for (; item != NULL; item = item->next_item) {
4488 		if (Xflag) {
4489 			(void) printf("[%4d] Group = %d, mib_id = %d, "
4490 			    "length = %d, valp = 0x%p\n", jtemp++,
4491 			    item->group, item->mib_id,
4492 			    item->length, item->valp);
4493 		}
4494 		if (!((item->group == MIB2_IP &&
4495 		    item->mib_id == MIB2_IP_ROUTE) ||
4496 		    (item->group == MIB2_IP6 &&
4497 		    item->mib_id == MIB2_IP6_ROUTE)))
4498 			continue;
4499 
4500 		if (item->group == MIB2_IP && !family_selected(AF_INET))
4501 			continue;
4502 		else if (item->group == MIB2_IP6 && !family_selected(AF_INET6))
4503 			continue;
4504 
4505 		if (Xflag) {
4506 			if (item->group == MIB2_IP) {
4507 				(void) printf("%u records for "
4508 				    "ipRouteEntryTable:\n",
4509 				    item->length/sizeof (mib2_ipRouteEntry_t));
4510 			} else {
4511 				(void) printf("%u records for "
4512 				    "ipv6RouteEntryTable:\n",
4513 				    item->length/
4514 				    sizeof (mib2_ipv6RouteEntry_t));
4515 			}
4516 		}
4517 
4518 		if (item->group == MIB2_IP) {
4519 			for (rp = (mib2_ipRouteEntry_t *)item->valp;
4520 			    (char *)rp < (char *)item->valp + item->length;
4521 			    rp = (mib2_ipRouteEntry_t *)((char *)rp +
4522 			    ipRouteEntrySize)) {
4523 				aptr = v4a == NULL ? NULL : *v4a++;
4524 				print_hdr_once_v4 = ire_report_item_v4(rp,
4525 				    print_hdr_once_v4, aptr);
4526 			}
4527 		} else {
4528 			for (rp6 = (mib2_ipv6RouteEntry_t *)item->valp;
4529 			    (char *)rp6 < (char *)item->valp + item->length;
4530 			    rp6 = (mib2_ipv6RouteEntry_t *)((char *)rp6 +
4531 			    ipv6RouteEntrySize)) {
4532 				aptr = v6a == NULL ? NULL : *v6a++;
4533 				print_hdr_once_v6 = ire_report_item_v6(rp6,
4534 				    print_hdr_once_v6, aptr);
4535 			}
4536 		}
4537 	}
4538 	(void) fflush(stdout);
4539 ire_report_done:
4540 	if (v4_attrs != NULL)
4541 		free(v4_attrs);
4542 	if (v6_attrs != NULL)
4543 		free(v6_attrs);
4544 	if (all_attrs != NULL)
4545 		free(all_attrs);
4546 }
4547 
4548 /*
4549  * Match a user-supplied device name.  We do this by string because
4550  * the MIB2 interface gives us interface name strings rather than
4551  * ifIndex numbers.  The "none" rule matches only routes with no
4552  * interface.  The "any" rule matches routes with any non-blank
4553  * interface.  A base name ("hme0") matches all aliases as well
4554  * ("hme0:1").
4555  */
4556 static boolean_t
4557 dev_name_match(const DeviceName *devnam, const char *ifname)
4558 {
4559 	int iflen;
4560 
4561 	if (ifname == NULL)
4562 		return (devnam->o_length == 0);		/* "none" */
4563 	if (*ifname == '\0')
4564 		return (devnam->o_length != 0);		/* "any" */
4565 	iflen = strlen(ifname);
4566 	/* The check for ':' here supports interface aliases. */
4567 	if (iflen > devnam->o_length ||
4568 	    (iflen < devnam->o_length && devnam->o_bytes[iflen] != ':'))
4569 		return (B_FALSE);
4570 	return (strncmp(ifname, devnam->o_bytes, iflen) == 0);
4571 }
4572 
4573 /*
4574  * Match a user-supplied IP address list.  The "any" rule matches any
4575  * non-zero address.  The "none" rule matches only the zero address.
4576  * IPv6 addresses supplied by the user are ignored.  If the user
4577  * supplies a subnet mask, then match routes that are at least that
4578  * specific (use the user's mask).  If the user supplies only an
4579  * address, then select any routes that would match (use the route's
4580  * mask).
4581  */
4582 static boolean_t
4583 v4_addr_match(IpAddress addr, IpAddress mask, const filter_t *fp)
4584 {
4585 	char **app;
4586 	char *aptr;
4587 	in_addr_t faddr, fmask;
4588 
4589 	if (fp->u.a.f_address == NULL) {
4590 		if (IN6_IS_ADDR_UNSPECIFIED(&fp->u.a.f_mask))
4591 			return (addr != INADDR_ANY);	/* "any" */
4592 		else
4593 			return (addr == INADDR_ANY);	/* "none" */
4594 	}
4595 	if (!IN6_IS_V4MASK(fp->u.a.f_mask))
4596 		return (B_FALSE);
4597 	IN6_V4MAPPED_TO_IPADDR(&fp->u.a.f_mask, fmask);
4598 	if (fmask != IP_HOST_MASK) {
4599 		if (fmask > mask)
4600 			return (B_FALSE);
4601 		mask = fmask;
4602 	}
4603 	for (app = fp->u.a.f_address->h_addr_list; (aptr = *app) != NULL; app++)
4604 		if (IN6_IS_ADDR_V4MAPPED((in6_addr_t *)aptr)) {
4605 			IN6_V4MAPPED_TO_IPADDR((in6_addr_t *)aptr, faddr);
4606 			if (((faddr ^ addr) & mask) == 0)
4607 				return (B_TRUE);
4608 		}
4609 	return (B_FALSE);
4610 }
4611 
4612 /*
4613  * Run through the filter list for an IPv4 MIB2 route entry.  If all
4614  * filters of a given type fail to match, then the route is filtered
4615  * out (not displayed).  If no filter is given or at least one filter
4616  * of each type matches, then display the route.
4617  */
4618 static boolean_t
4619 ire_filter_match_v4(const mib2_ipRouteEntry_t *rp, uint_t flag_b)
4620 {
4621 	filter_t *fp;
4622 	int idx;
4623 
4624 	for (idx = 0; idx < NFILTERKEYS; idx++)
4625 		if ((fp = filters[idx]) != NULL) {
4626 			for (; fp != NULL; fp = fp->f_next) {
4627 				switch (idx) {
4628 				case FK_AF:
4629 					if (fp->u.f_family != AF_INET)
4630 						continue;
4631 					break;
4632 				case FK_OUTIF:
4633 					if (!dev_name_match(&rp->ipRouteIfIndex,
4634 					    fp->u.f_ifname))
4635 						continue;
4636 					break;
4637 				case FK_DST:
4638 					if (!v4_addr_match(rp->ipRouteDest,
4639 					    rp->ipRouteMask, fp))
4640 						continue;
4641 					break;
4642 				case FK_FLAGS:
4643 					if ((flag_b & fp->u.f.f_flagset) !=
4644 					    fp->u.f.f_flagset ||
4645 					    (flag_b & fp->u.f.f_flagclear))
4646 						continue;
4647 					break;
4648 				}
4649 				break;
4650 			}
4651 			if (fp == NULL)
4652 				return (B_FALSE);
4653 		}
4654 	return (B_TRUE);
4655 }
4656 
4657 /*
4658  * Given an IPv4 MIB2 route entry, form the list of flags for the
4659  * route.
4660  */
4661 static uint_t
4662 form_v4_route_flags(const mib2_ipRouteEntry_t *rp, char *flags)
4663 {
4664 	uint_t flag_b;
4665 
4666 	flag_b = FLF_U;
4667 	(void) strcpy(flags, "U");
4668 	/* RTF_INDIRECT wins over RTF_GATEWAY - don't display both */
4669 	if (rp->ipRouteInfo.re_flags & RTF_INDIRECT) {
4670 		(void) strcat(flags, "I");
4671 		flag_b |= FLF_I;
4672 	} else if (rp->ipRouteInfo.re_ire_type & IRE_OFFLINK) {
4673 		(void) strcat(flags, "G");
4674 		flag_b |= FLF_G;
4675 	}
4676 	/* IRE_IF_CLONE wins over RTF_HOST - don't display both */
4677 	if (rp->ipRouteInfo.re_ire_type & IRE_IF_CLONE) {
4678 		(void) strcat(flags, "C");
4679 		flag_b |= FLF_C;
4680 	} else if (rp->ipRouteMask == IP_HOST_MASK) {
4681 		(void) strcat(flags, "H");
4682 		flag_b |= FLF_H;
4683 	}
4684 	if (rp->ipRouteInfo.re_flags & RTF_DYNAMIC) {
4685 		(void) strcat(flags, "D");
4686 		flag_b |= FLF_D;
4687 	}
4688 	if (rp->ipRouteInfo.re_ire_type == IRE_BROADCAST) {	/* Broadcast */
4689 		(void) strcat(flags, "b");
4690 		flag_b |= FLF_b;
4691 	}
4692 	if (rp->ipRouteInfo.re_ire_type == IRE_LOCAL) {		/* Local */
4693 		(void) strcat(flags, "L");
4694 		flag_b |= FLF_L;
4695 	}
4696 	if (rp->ipRouteInfo.re_flags & RTF_MULTIRT) {
4697 		(void) strcat(flags, "M");			/* Multiroute */
4698 		flag_b |= FLF_M;
4699 	}
4700 	if (rp->ipRouteInfo.re_flags & RTF_SETSRC) {
4701 		(void) strcat(flags, "S");			/* Setsrc */
4702 		flag_b |= FLF_S;
4703 	}
4704 	if (rp->ipRouteInfo.re_flags & RTF_REJECT) {
4705 		(void) strcat(flags, "R");
4706 		flag_b |= FLF_R;
4707 	}
4708 	if (rp->ipRouteInfo.re_flags & RTF_BLACKHOLE) {
4709 		(void) strcat(flags, "B");
4710 		flag_b |= FLF_B;
4711 	}
4712 	if (rp->ipRouteInfo.re_flags & RTF_ZONE) {
4713 		(void) strcat(flags, "Z");
4714 		flag_b |= FLF_Z;
4715 	}
4716 	return (flag_b);
4717 }
4718 
4719 /*
4720  * Central definitions for the columns used in the reports.
4721  * For each column, there's a definition for the heading, the underline and
4722  * the formatted value.
4723  * Since most reports select different columns depending on command line
4724  * options, defining everything here avoids duplication in the report
4725  * format strings and makes it easy to make changes as necessary.
4726  */
4727 #define	IRE_V4_DEST		"  Destination       "
4728 #define	IRE_V4_DEST_		"--------------------"
4729 #define	IRE_V4_DEST_F		"%-20s"
4730 #define	IRE_V4_MASK		"     Mask      "
4731 #define	IRE_V4_MASK_		"---------------"
4732 #define	IRE_V4_MASK_F		"%-15s"
4733 #define	IRE_V4_GATEWAY		"    Gateway         "
4734 #define	IRE_V4_GATEWAY_		"--------------------"
4735 #define	IRE_V4_GATEWAY_F	"%-20s"
4736 #define	IRE_V4_DEVICE		"Device"
4737 #define	IRE_V4_DEVICE_		"------"
4738 #define	IRE_V4_DEVICE_F		"%-6s"
4739 #define	IRE_V4_MTU		" MTU "
4740 #define	IRE_V4_MTU_		"-----"
4741 #define	IRE_V4_MTU_F		"%5u"
4742 #define	IRE_V4_REF		"Ref"
4743 #define	IRE_V4_REF_		"---"
4744 #define	IRE_V4_REF_F		"%3u"
4745 #define	IRE_V4_FLAGS		"Flg"
4746 #define	IRE_V4_FLAGS_		"---"
4747 #define	IRE_V4_FLAGS_F		"%-4s"
4748 #define	IRE_V4_OUT		" Out  "
4749 #define	IRE_V4_OUT_		"------"
4750 #define	IRE_V4_OUT_F		"%-6s"
4751 #define	IRE_V4_INFWD		"In/Fwd"
4752 #define	IRE_V4_INFWD_		"------"
4753 #define	IRE_V4_INFWD_F		"%6u"
4754 #define	IRE_V4_LFLAGS		"Flags"
4755 #define	IRE_V4_LFLAGS_		"-----"
4756 #define	IRE_V4_LFLAGS_F		"%-5s"
4757 #define	IRE_V4_LREF		" Ref "
4758 #define	IRE_V4_LREF_		"-----"
4759 #define	IRE_V4_LREF_F		" %4u"
4760 #define	IRE_V4_USE		"   Use    "
4761 #define	IRE_V4_USE_		"----------"
4762 #define	IRE_V4_USE_F		"%10u"
4763 #define	IRE_V4_INTERFACE	"Interface"
4764 #define	IRE_V4_INTERFACE_	"---------"
4765 #define	IRE_V4_INTERFACE_F	"%-9s"
4766 
4767 static const char ire_hdr_v4[] =
4768 "\n%s Table: IPv4\n";
4769 static const char ire_hdr_v4_compat[] =
4770 "\n%s Table:\n";
4771 
4772 static const char ire_hdr_v4_verbose[] =
4773     IRE_V4_DEST " " IRE_V4_MASK " " IRE_V4_GATEWAY " " IRE_V4_DEVICE " "
4774     IRE_V4_MTU " " IRE_V4_REF " " IRE_V4_FLAGS " "
4775     IRE_V4_OUT " " IRE_V4_INFWD " %s\n"
4776     IRE_V4_DEST_" " IRE_V4_MASK_" " IRE_V4_GATEWAY_" " IRE_V4_DEVICE_" "
4777     IRE_V4_MTU_" " IRE_V4_REF_" " IRE_V4_FLAGS_" "
4778     IRE_V4_OUT_" " IRE_V4_INFWD_" %s\n";
4779 
4780 static const char ire_hdr_v4_normal[] =
4781     IRE_V4_DEST " " IRE_V4_GATEWAY " "
4782     IRE_V4_LFLAGS " " IRE_V4_LREF " " IRE_V4_USE " "
4783     IRE_V4_INTERFACE " %s\n"
4784     IRE_V4_DEST_" " IRE_V4_GATEWAY_" "
4785     IRE_V4_LFLAGS_" " IRE_V4_LREF_" " IRE_V4_USE_" "
4786     IRE_V4_INTERFACE_" %s\n";
4787 
4788 static boolean_t
4789 ire_report_item_v4(const mib2_ipRouteEntry_t *rp, boolean_t first,
4790     const sec_attr_list_t *attrs)
4791 {
4792 	char			dstbuf[MAXHOSTNAMELEN + 4]; /* + "/<num>" */
4793 	char			maskbuf[MAXHOSTNAMELEN + 1];
4794 	char			gwbuf[MAXHOSTNAMELEN + 1];
4795 	char			ifname[LIFNAMSIZ + 1];
4796 	char			flags[10];	/* RTF_ flags */
4797 	uint_t			flag_b;
4798 
4799 	if (!(Aflag || (rp->ipRouteInfo.re_ire_type != IRE_IF_CLONE &&
4800 	    rp->ipRouteInfo.re_ire_type != IRE_BROADCAST &&
4801 	    rp->ipRouteInfo.re_ire_type != IRE_MULTICAST &&
4802 	    rp->ipRouteInfo.re_ire_type != IRE_NOROUTE &&
4803 	    rp->ipRouteInfo.re_ire_type != IRE_LOCAL))) {
4804 		return (first);
4805 	}
4806 
4807 	flag_b = form_v4_route_flags(rp, flags);
4808 
4809 	if (!ire_filter_match_v4(rp, flag_b))
4810 		return (first);
4811 
4812 	if (first) {
4813 		(void) printf(v4compat ? ire_hdr_v4_compat : ire_hdr_v4,
4814 		    Vflag ? "IRE" : "Routing");
4815 		(void) printf(Vflag ? ire_hdr_v4_verbose : ire_hdr_v4_normal,
4816 		    RSECflag ? "  Gateway security attributes  " : "",
4817 		    RSECflag ? "-------------------------------" : "");
4818 		first = B_FALSE;
4819 	}
4820 
4821 	if (flag_b & FLF_H) {
4822 		(void) pr_addr(rp->ipRouteDest, dstbuf, sizeof (dstbuf));
4823 	} else {
4824 		(void) pr_net(rp->ipRouteDest, rp->ipRouteMask,
4825 		    dstbuf, sizeof (dstbuf));
4826 	}
4827 	if (Vflag) {
4828 		(void) printf(
4829 		    IRE_V4_DEST_F " " IRE_V4_MASK_F " " IRE_V4_GATEWAY_F " "
4830 		    IRE_V4_DEVICE_F " " IRE_V4_MTU_F " " IRE_V4_REF_F " "
4831 		    IRE_V4_FLAGS_F IRE_V4_INFWD_F " " IRE_V4_INFWD_F " %s\n",
4832 		    dstbuf,
4833 		    pr_mask(rp->ipRouteMask, maskbuf, sizeof (maskbuf)),
4834 		    pr_addrnz(rp->ipRouteNextHop, gwbuf, sizeof (gwbuf)),
4835 		    octetstr(&rp->ipRouteIfIndex, 'a', ifname, sizeof (ifname)),
4836 		    rp->ipRouteInfo.re_max_frag,
4837 		    rp->ipRouteInfo.re_ref,
4838 		    flags,
4839 		    rp->ipRouteInfo.re_obpkt,
4840 		    rp->ipRouteInfo.re_ibpkt,
4841 		    pr_secattr(attrs));
4842 	} else {
4843 		(void) printf(
4844 		    IRE_V4_DEST_F " " IRE_V4_GATEWAY_F " "
4845 		    IRE_V4_LFLAGS_F " " IRE_V4_LREF_F " "
4846 		    IRE_V4_USE_F " " IRE_V4_INTERFACE_F " %s\n",
4847 		    dstbuf,
4848 		    pr_addrnz(rp->ipRouteNextHop, gwbuf, sizeof (gwbuf)),
4849 		    flags,
4850 		    rp->ipRouteInfo.re_ref,
4851 		    rp->ipRouteInfo.re_obpkt + rp->ipRouteInfo.re_ibpkt,
4852 		    octetstr(&rp->ipRouteIfIndex, 'a',
4853 		    ifname, sizeof (ifname)),
4854 		    pr_secattr(attrs));
4855 	}
4856 	return (first);
4857 }
4858 
4859 /*
4860  * Match a user-supplied IP address list against an IPv6 route entry.
4861  * If the user specified "any," then any non-zero address matches.  If
4862  * the user specified "none," then only the zero address matches.  If
4863  * the user specified a subnet mask length, then use that in matching
4864  * routes (select routes that are at least as specific).  If the user
4865  * specified only an address, then use the route's mask (select routes
4866  * that would match that address).  IPv4 addresses are ignored.
4867  */
4868 static boolean_t
4869 v6_addr_match(const Ip6Address *addr, int masklen, const filter_t *fp)
4870 {
4871 	const uint8_t *ucp;
4872 	int fmasklen;
4873 	int i;
4874 	char **app;
4875 	const uint8_t *aptr;
4876 
4877 	if (fp->u.a.f_address == NULL) {
4878 		if (IN6_IS_ADDR_UNSPECIFIED(&fp->u.a.f_mask))	/* any */
4879 			return (!IN6_IS_ADDR_UNSPECIFIED(addr));
4880 		return (IN6_IS_ADDR_UNSPECIFIED(addr));		/* "none" */
4881 	}
4882 	fmasklen = 0;
4883 	for (ucp = fp->u.a.f_mask.s6_addr;
4884 	    ucp < fp->u.a.f_mask.s6_addr + sizeof (fp->u.a.f_mask.s6_addr);
4885 	    ucp++) {
4886 		if (*ucp != 0xff) {
4887 			if (*ucp != 0)
4888 				fmasklen += 9 - ffs(*ucp);
4889 			break;
4890 		}
4891 		fmasklen += 8;
4892 	}
4893 	if (fmasklen != IPV6_ABITS) {
4894 		if (fmasklen > masklen)
4895 			return (B_FALSE);
4896 		masklen = fmasklen;
4897 	}
4898 	for (app = fp->u.a.f_address->h_addr_list;
4899 	    (aptr = (uint8_t *)*app) != NULL; app++) {
4900 		if (IN6_IS_ADDR_V4MAPPED((in6_addr_t *)aptr))
4901 			continue;
4902 		ucp = addr->s6_addr;
4903 		for (i = masklen; i >= 8; i -= 8)
4904 			if (*ucp++ != *aptr++)
4905 				break;
4906 		if (i == 0 ||
4907 		    (i < 8 && ((*ucp ^ *aptr) & ~(0xff >> i)) == 0))
4908 			return (B_TRUE);
4909 	}
4910 	return (B_FALSE);
4911 }
4912 
4913 /*
4914  * Run through the filter list for an IPv6 MIB2 IRE.  For a given
4915  * type, if there's at least one filter and all filters of that type
4916  * fail to match, then the route doesn't match and isn't displayed.
4917  * If at least one matches, or none are specified, for each of the
4918  * types, then the route is selected and displayed.
4919  */
4920 static boolean_t
4921 ire_filter_match_v6(const mib2_ipv6RouteEntry_t *rp6, uint_t flag_b)
4922 {
4923 	filter_t *fp;
4924 	int idx;
4925 
4926 	for (idx = 0; idx < NFILTERKEYS; idx++)
4927 		if ((fp = filters[idx]) != NULL) {
4928 			for (; fp != NULL; fp = fp->f_next) {
4929 				switch (idx) {
4930 				case FK_AF:
4931 					if (fp->u.f_family != AF_INET6)
4932 						continue;
4933 					break;
4934 				case FK_OUTIF:
4935 					if (!dev_name_match(&rp6->
4936 					    ipv6RouteIfIndex, fp->u.f_ifname))
4937 						continue;
4938 					break;
4939 				case FK_DST:
4940 					if (!v6_addr_match(&rp6->ipv6RouteDest,
4941 					    rp6->ipv6RoutePfxLength, fp))
4942 						continue;
4943 					break;
4944 				case FK_FLAGS:
4945 					if ((flag_b & fp->u.f.f_flagset) !=
4946 					    fp->u.f.f_flagset ||
4947 					    (flag_b & fp->u.f.f_flagclear))
4948 						continue;
4949 					break;
4950 				}
4951 				break;
4952 			}
4953 			if (fp == NULL)
4954 				return (B_FALSE);
4955 		}
4956 	return (B_TRUE);
4957 }
4958 
4959 /*
4960  * Given an IPv6 MIB2 route entry, form the list of flags for the
4961  * route.
4962  */
4963 static uint_t
4964 form_v6_route_flags(const mib2_ipv6RouteEntry_t *rp6, char *flags)
4965 {
4966 	uint_t flag_b;
4967 
4968 	flag_b = FLF_U;
4969 	(void) strcpy(flags, "U");
4970 	/* RTF_INDIRECT wins over RTF_GATEWAY - don't display both */
4971 	if (rp6->ipv6RouteInfo.re_flags & RTF_INDIRECT) {
4972 		(void) strcat(flags, "I");
4973 		flag_b |= FLF_I;
4974 	} else if (rp6->ipv6RouteInfo.re_ire_type & IRE_OFFLINK) {
4975 		(void) strcat(flags, "G");
4976 		flag_b |= FLF_G;
4977 	}
4978 
4979 	/* IRE_IF_CLONE wins over RTF_HOST - don't display both */
4980 	if (rp6->ipv6RouteInfo.re_ire_type & IRE_IF_CLONE) {
4981 		(void) strcat(flags, "C");
4982 		flag_b |= FLF_C;
4983 	} else if (rp6->ipv6RoutePfxLength == IPV6_ABITS) {
4984 		(void) strcat(flags, "H");
4985 		flag_b |= FLF_H;
4986 	}
4987 
4988 	if (rp6->ipv6RouteInfo.re_flags & RTF_DYNAMIC) {
4989 		(void) strcat(flags, "D");
4990 		flag_b |= FLF_D;
4991 	}
4992 	if (rp6->ipv6RouteInfo.re_ire_type == IRE_LOCAL) {	/* Local */
4993 		(void) strcat(flags, "L");
4994 		flag_b |= FLF_L;
4995 	}
4996 	if (rp6->ipv6RouteInfo.re_flags & RTF_MULTIRT) {
4997 		(void) strcat(flags, "M");			/* Multiroute */
4998 		flag_b |= FLF_M;
4999 	}
5000 	if (rp6->ipv6RouteInfo.re_flags & RTF_SETSRC) {
5001 		(void) strcat(flags, "S");			/* Setsrc */
5002 		flag_b |= FLF_S;
5003 	}
5004 	if (rp6->ipv6RouteInfo.re_flags & RTF_REJECT) {
5005 		(void) strcat(flags, "R");
5006 		flag_b |= FLF_R;
5007 	}
5008 	if (rp6->ipv6RouteInfo.re_flags & RTF_BLACKHOLE) {
5009 		(void) strcat(flags, "B");
5010 		flag_b |= FLF_B;
5011 	}
5012 	if (rp6->ipv6RouteInfo.re_flags & RTF_ZONE) {
5013 		(void) strcat(flags, "Z");
5014 		flag_b |= FLF_Z;
5015 	}
5016 	return (flag_b);
5017 }
5018 
5019 /*
5020  * Central definitions for the columns used in the reports.
5021  * For each column, there's a definition for the heading, the underline and
5022  * the formatted value.
5023  * Since most reports select different columns depending on command line
5024  * options, defining everything here avoids duplication in the report
5025  * format strings and makes it easy to make changes as necessary.
5026  */
5027 #define	IRE_V6_DEST		"  Destination/Mask         "
5028 #define	IRE_V6_DEST_		"---------------------------"
5029 #define	IRE_V6_DEST_F		"%-27s"
5030 #define	IRE_V6_GATEWAY		"  Gateway                  "
5031 #define	IRE_V6_GATEWAY_		"---------------------------"
5032 #define	IRE_V6_GATEWAY_F	"%-27s"
5033 #define	IRE_V6_IF		" If  "
5034 #define	IRE_V6_IF_		"-----"
5035 #define	IRE_V6_IF_F		"%-5s"
5036 #define	IRE_V6_MTU		" MTU "
5037 #define	IRE_V6_MTU_		"-----"
5038 #define	IRE_V6_MTU_F		"%5u"
5039 #define	IRE_V6_REF		"Ref"
5040 #define	IRE_V6_REF_		"---"
5041 #define	IRE_V6_REF_F		"%3u"
5042 #define	IRE_V6_USE		"  Use  "
5043 #define	IRE_V6_USE_		"-------"
5044 #define	IRE_V6_USE_F		"%7u"
5045 #define	IRE_V6_FLAGS		"Flags"
5046 #define	IRE_V6_FLAGS_		"-----"
5047 #define	IRE_V6_FLAGS_F		"%-5s"
5048 #define	IRE_V6_OUT		" Out  "
5049 #define	IRE_V6_OUT_		"------"
5050 #define	IRE_V6_OUT_F		"%6u"
5051 #define	IRE_V6_INFWD		"In/Fwd"
5052 #define	IRE_V6_INFWD_		"------"
5053 #define	IRE_V6_INFWD_F		"%6u"
5054 
5055 static const char ire_hdr_v6[] =
5056 "\n%s Table: IPv6\n";
5057 static const char ire_hdr_v6_verbose[] =
5058     IRE_V6_DEST " " IRE_V6_GATEWAY " " IRE_V6_IF " " IRE_V6_MTU " "
5059     IRE_V6_REF " " IRE_V6_FLAGS " " IRE_V6_OUT " " IRE_V6_INFWD " %s\n"
5060     IRE_V6_DEST_" " IRE_V6_GATEWAY_" " IRE_V6_IF_" " IRE_V6_MTU_" "
5061     IRE_V6_REF_" " IRE_V6_FLAGS_" " IRE_V6_OUT_" " IRE_V6_INFWD_" %s\n";
5062 static const char ire_hdr_v6_normal[] =
5063     IRE_V6_DEST " " IRE_V6_GATEWAY " "
5064     IRE_V6_FLAGS " " IRE_V6_REF " " IRE_V6_USE " " IRE_V6_IF " %s\n"
5065     IRE_V6_DEST_" " IRE_V6_GATEWAY_" "
5066     IRE_V6_FLAGS_" " IRE_V6_REF_" " IRE_V6_USE_" " IRE_V6_IF_" %s\n";
5067 
5068 static boolean_t
5069 ire_report_item_v6(const mib2_ipv6RouteEntry_t *rp6, boolean_t first,
5070     const sec_attr_list_t *attrs)
5071 {
5072 	char			dstbuf[MAXHOSTNAMELEN + 1];
5073 	char			gwbuf[MAXHOSTNAMELEN + 1];
5074 	char			ifname[LIFNAMSIZ + 1];
5075 	char			flags[10];	/* RTF_ flags */
5076 	uint_t			flag_b;
5077 
5078 	if (!(Aflag || (rp6->ipv6RouteInfo.re_ire_type != IRE_IF_CLONE &&
5079 	    rp6->ipv6RouteInfo.re_ire_type != IRE_MULTICAST &&
5080 	    rp6->ipv6RouteInfo.re_ire_type != IRE_NOROUTE &&
5081 	    rp6->ipv6RouteInfo.re_ire_type != IRE_LOCAL))) {
5082 		return (first);
5083 	}
5084 
5085 	flag_b = form_v6_route_flags(rp6, flags);
5086 
5087 	if (!ire_filter_match_v6(rp6, flag_b))
5088 		return (first);
5089 
5090 	if (first) {
5091 		(void) printf(ire_hdr_v6, Vflag ? "IRE" : "Routing");
5092 		(void) printf(Vflag ? ire_hdr_v6_verbose : ire_hdr_v6_normal,
5093 		    RSECflag ? "  Gateway security attributes  " : "",
5094 		    RSECflag ? "-------------------------------" : "");
5095 		first = B_FALSE;
5096 	}
5097 
5098 	if (Vflag) {
5099 		(void) printf(
5100 		    IRE_V6_DEST_F " " IRE_V6_GATEWAY_F " "
5101 		    IRE_V6_IF_F " " IRE_V6_MTU_F " " IRE_V6_REF_F " "
5102 		    IRE_V6_FLAGS_F " " IRE_V6_OUT_F " " IRE_V6_INFWD_F " %s\n",
5103 		    pr_prefix6(&rp6->ipv6RouteDest,
5104 		    rp6->ipv6RoutePfxLength, dstbuf, sizeof (dstbuf)),
5105 		    IN6_IS_ADDR_UNSPECIFIED(&rp6->ipv6RouteNextHop) ?
5106 		    "    --" :
5107 		    pr_addr6(&rp6->ipv6RouteNextHop, gwbuf, sizeof (gwbuf)),
5108 		    octetstr(&rp6->ipv6RouteIfIndex, 'a',
5109 		    ifname, sizeof (ifname)),
5110 		    rp6->ipv6RouteInfo.re_max_frag,
5111 		    rp6->ipv6RouteInfo.re_ref,
5112 		    flags,
5113 		    rp6->ipv6RouteInfo.re_obpkt,
5114 		    rp6->ipv6RouteInfo.re_ibpkt,
5115 		    pr_secattr(attrs));
5116 	} else {
5117 		(void) printf(
5118 		    IRE_V6_DEST_F " " IRE_V6_GATEWAY_F " "
5119 		    IRE_V6_FLAGS_F " " IRE_V6_REF_F " "
5120 		    IRE_V6_USE_F " " IRE_V6_IF_F " %s\n",
5121 		    pr_prefix6(&rp6->ipv6RouteDest,
5122 		    rp6->ipv6RoutePfxLength, dstbuf, sizeof (dstbuf)),
5123 		    IN6_IS_ADDR_UNSPECIFIED(&rp6->ipv6RouteNextHop) ?
5124 		    "    --" :
5125 		    pr_addr6(&rp6->ipv6RouteNextHop, gwbuf, sizeof (gwbuf)),
5126 		    flags,
5127 		    rp6->ipv6RouteInfo.re_ref,
5128 		    rp6->ipv6RouteInfo.re_obpkt + rp6->ipv6RouteInfo.re_ibpkt,
5129 		    octetstr(&rp6->ipv6RouteIfIndex, 'a',
5130 		    ifname, sizeof (ifname)),
5131 		    pr_secattr(attrs));
5132 	}
5133 	return (first);
5134 }
5135 
5136 /*
5137  * Common attribute-gathering routine for all transports.
5138  */
5139 static mib2_transportMLPEntry_t **
5140 gather_attrs(const mib_item_t *item, int group, int mib_id, int esize)
5141 {
5142 	size_t transport_count = 0;
5143 	const mib_item_t *iptr;
5144 	mib2_transportMLPEntry_t **attrs, *tme;
5145 
5146 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
5147 		if (iptr->group == group && iptr->mib_id == mib_id) {
5148 			size_t els = iptr->length / esize;
5149 			if (transport_count > SIZE_MAX - els) {
5150 				fprintf(stderr, "Connection table too large\n");
5151 				return (NULL);
5152 			} else {
5153 				transport_count += els;
5154 			}
5155 		}
5156 	}
5157 
5158 	if (transport_count == 0)
5159 		return (NULL);
5160 
5161 	attrs = recallocarray(NULL, 0, transport_count, sizeof (*attrs));
5162 
5163 	if (attrs == NULL) {
5164 		perror("gather_attrs allocation failed");
5165 		return (NULL);
5166 	}
5167 
5168 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
5169 		if (iptr->group == group && iptr->mib_id == EXPER_XPORT_MLP) {
5170 			for (tme = iptr->valp;
5171 			    (char *)tme < (char *)iptr->valp + iptr->length;
5172 			    tme = (mib2_transportMLPEntry_t *)((char *)tme +
5173 			    transportMLPSize)) {
5174 				attrs[tme->tme_connidx] = tme;
5175 			}
5176 		}
5177 	}
5178 	return (attrs);
5179 }
5180 
5181 static void
5182 sie_report(const mib2_socketInfoEntry_t *sie)
5183 {
5184 	if (sie == NULL)
5185 		return;
5186 
5187 	(void) printf("INFO[%" PRIu64 "] = "
5188 	    "inode %" PRIu64 ", "
5189 	    "major %" PRIx32 ", "
5190 	    "flags %#" PRIx64 "\n",
5191 	    sie->sie_connidx, sie->sie_inode,
5192 	    major((dev_t)sie->sie_dev), sie->sie_flags);
5193 }
5194 
5195 /*
5196  * Common info-gathering routine for all transports.
5197  *
5198  * The linked list of MIB data pointed to by item consists of a number of
5199  * tables covering several protocol families and socket types, one after
5200  * another. These are generally tables containing information about network
5201  * connections, such as mib2_tcpConnEntry, as defined in RFC 1213/4022.
5202  *
5203  * There are also ancilliary tables which contain optional additional
5204  * information about each socket. The data in these ancilliary tables is
5205  * indexed by the table position of the connection to which it relates, and
5206  * data may not be available for all connections.
5207  *
5208  * The code here determines the size of the connection table, allocates an
5209  * array of that size to hold the ancilliary data and then fills that in
5210  * if data is present.
5211  *
5212  * As an example, if the data contains a mib2_tcpConnEntry table containing
5213  * three connections, but there is no ancilliary data for the second, then
5214  * the accompanying mib2_socketInfoEntry table will only contain two entries.
5215  * However, the first entry is tagged as referring to connection slot 0, and
5216  * the second is tagged with connection slot 2.
5217  * This function would return an array with:
5218  * { <data for conn0>, NULL, <data for conn2> }
5219  *
5220  */
5221 static mib2_socketInfoEntry_t **
5222 gather_info(const mib_item_t *item, int group, int mib_id, int esize)
5223 {
5224 	size_t transport_count = 0;
5225 	const mib_item_t *iptr;
5226 	mib2_socketInfoEntry_t **info, *sie;
5227 
5228 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
5229 		if (iptr->group == group && iptr->mib_id == mib_id) {
5230 			size_t els = iptr->length / esize;
5231 			if (transport_count > SIZE_MAX - els) {
5232 				fprintf(stderr, "Connection table too large\n");
5233 				return (NULL);
5234 			} else {
5235 				transport_count += els;
5236 			}
5237 		}
5238 	}
5239 
5240 	if (transport_count == 0)
5241 		return (NULL);
5242 
5243 	info = recallocarray(NULL, 0, transport_count, sizeof (*info));
5244 
5245 	if (info == NULL) {
5246 		perror("gather_info allocation failed");
5247 		return (NULL);
5248 	}
5249 
5250 	for (iptr = item; iptr != NULL; iptr = iptr->next_item) {
5251 		if (iptr->group != group || iptr->mib_id != EXPER_SOCK_INFO)
5252 			continue;
5253 
5254 		for (sie = (mib2_socketInfoEntry_t *)iptr->valp;
5255 		    (uintptr_t)sie < (uintptr_t)iptr->valp + iptr->length;
5256 		    sie++) {
5257 			assert(sie->sie_connidx < transport_count);
5258 			info[sie->sie_connidx] = sie;
5259 		}
5260 	}
5261 	return (info);
5262 }
5263 
5264 static void
5265 print_transport_label(const mib2_transportMLPEntry_t *attr)
5266 {
5267 	if (!RSECflag || attr == NULL ||
5268 	    !(attr->tme_flags & MIB2_TMEF_IS_LABELED))
5269 		return;
5270 
5271 	if (bisinvalid(&attr->tme_label)) {
5272 		(void) printf("   INVALID\n");
5273 	} else if (!blequal(&attr->tme_label, zone_security_label)) {
5274 		char *sl_str;
5275 
5276 		sl_str = sl_to_str(&attr->tme_label);
5277 		(void) printf("   %s\n", sl_str);
5278 		free(sl_str);
5279 	}
5280 }
5281 
5282 /* ------------------------------ TCP_REPORT------------------------------- */
5283 
5284 static const char tcp_hdr_v4[] =
5285 "\nTCP: IPv4\n";
5286 static const char tcp_hdr_v4_compat[] =
5287 "\nTCP\n";
5288 
5289 /*
5290  * Central definitions for the columns used in the reports.
5291  * For each column, there's a definition for the heading, the underline and
5292  * the formatted value.
5293  * Since most reports select different columns depending on command line
5294  * options, defining everything here avoids duplication in the report
5295  * format strings and makes it easy to make changes as necessary.
5296  */
5297 #define	TCP_V4_LOCAL		"   Local Address    "
5298 #define	TCP_V4_LOCAL_		"--------------------"
5299 #define	TCP_V4_LOCAL_F		"%-20s"
5300 #define	TCP_V4_REMOTE		"   Remote Address   "
5301 #define	TCP_V4_REMOTE_		"--------------------"
5302 #define	TCP_V4_REMOTE_F		"%-20s"
5303 #define	TCP_V4_ADDRESS		"Local/Remote Address"
5304 #define	TCP_V4_ADDRESS_		"--------------------"
5305 #define	TCP_V4_ADDRESS_F	"%-20s"
5306 #define	TCP_V4_SWIND		"Swind "
5307 #define	TCP_V4_SWIND_		"------"
5308 #define	TCP_V4_SWIND_F		"%6u"
5309 #define	TCP_V4_SENDQ		"Send-Q"
5310 #define	TCP_V4_SENDQ_		"------"
5311 #define	TCP_V4_SENDQ_F		"%6" PRId64
5312 #define	TCP_V4_RWIND		"Rwind "
5313 #define	TCP_V4_RWIND_		"------"
5314 #define	TCP_V4_RWIND_F		"%6u"
5315 #define	TCP_V4_RECVQ		"Recv-Q"
5316 #define	TCP_V4_RECVQ_		"------"
5317 #define	TCP_V4_RECVQ_F		"%6" PRId64
5318 #define	TCP_V4_SNEXT		" Snext  "
5319 #define	TCP_V4_SNEXT_		"--------"
5320 #define	TCP_V4_SNEXT_F		"%08x"
5321 #define	TCP_V4_SUNA		"  Suna  "
5322 #define	TCP_V4_SUNA_		"--------"
5323 #define	TCP_V4_SUNA_F		"%08x"
5324 #define	TCP_V4_RNEXT		" Rnext  "
5325 #define	TCP_V4_RNEXT_		"--------"
5326 #define	TCP_V4_RNEXT_F		"%08x"
5327 #define	TCP_V4_RACK		"  Rack  "
5328 #define	TCP_V4_RACK_		"--------"
5329 #define	TCP_V4_RACK_F		"%08x"
5330 #define	TCP_V4_RTO		" Rto "
5331 #define	TCP_V4_RTO_		"-----"
5332 #define	TCP_V4_RTO_F		"%5u"
5333 #define	TCP_V4_MSS		" Mss "
5334 #define	TCP_V4_MSS_		"-----"
5335 #define	TCP_V4_MSS_F		"%5u"
5336 #define	TCP_V4_STATE		"   State   "
5337 #define	TCP_V4_STATE_		"-----------"
5338 #define	TCP_V4_STATE_F		"%-11s"
5339 #define	TCP_V4_USER		"  User  "
5340 #define	TCP_V4_USER_		"--------"
5341 #define	TCP_V4_USER_F		"%-8.8s"
5342 #define	TCP_V4_PID		" Pid  "
5343 #define	TCP_V4_PID_		"------"
5344 #define	TCP_V4_PID_F		"%6s"
5345 #define	TCP_V4_COMMAND		"   Command    "
5346 #define	TCP_V4_COMMAND_		"--------------"
5347 #define	TCP_V4_COMMAND_F	"%-14.14s"
5348 
5349 static const char tcp_hdr_v4_normal[] =
5350     TCP_V4_LOCAL " " TCP_V4_REMOTE " "
5351     TCP_V4_SWIND " " TCP_V4_SENDQ " " TCP_V4_RWIND " " TCP_V4_RECVQ " "
5352     TCP_V4_STATE "\n"
5353     TCP_V4_LOCAL_" " TCP_V4_REMOTE_" "
5354     TCP_V4_SWIND_" " TCP_V4_SENDQ_" " TCP_V4_RWIND_" " TCP_V4_RECVQ_" "
5355     TCP_V4_STATE_"\n";
5356 static const char tcp_hdr_v4_normal_pid[] =
5357     TCP_V4_LOCAL " " TCP_V4_REMOTE " "
5358     TCP_V4_USER " " TCP_V4_PID " " TCP_V4_COMMAND " "
5359     TCP_V4_SWIND " " TCP_V4_SENDQ " " TCP_V4_RWIND " " TCP_V4_RECVQ " "
5360     TCP_V4_STATE "\n"
5361     TCP_V4_LOCAL_" " TCP_V4_REMOTE_" "
5362     TCP_V4_USER_" " TCP_V4_PID_" " TCP_V4_COMMAND_" "
5363     TCP_V4_SWIND_" " TCP_V4_SENDQ_" " TCP_V4_RWIND_" " TCP_V4_RECVQ_" "
5364     TCP_V4_STATE_"\n";
5365 static const char tcp_hdr_v4_verbose[] =
5366     TCP_V4_ADDRESS " "
5367     TCP_V4_SWIND " " TCP_V4_SNEXT " " TCP_V4_SUNA " "
5368     TCP_V4_RWIND " " TCP_V4_RNEXT " " TCP_V4_RACK " "
5369     TCP_V4_RTO " " TCP_V4_MSS " " TCP_V4_STATE "\n"
5370     TCP_V4_ADDRESS_" "
5371     TCP_V4_SWIND_" " TCP_V4_SNEXT_" " TCP_V4_SUNA_" "
5372     TCP_V4_RWIND_" " TCP_V4_RNEXT_" " TCP_V4_RACK_" "
5373     TCP_V4_RTO_" " TCP_V4_MSS_" " TCP_V4_STATE_"\n";
5374 static const char tcp_hdr_v4_verbose_pid[] =
5375     TCP_V4_ADDRESS " "
5376     TCP_V4_SWIND " " TCP_V4_SNEXT " " TCP_V4_SUNA " "
5377     TCP_V4_RWIND " " TCP_V4_RNEXT " " TCP_V4_RACK " "
5378     TCP_V4_RTO " " TCP_V4_MSS " " TCP_V4_STATE " "
5379     TCP_V4_USER " " TCP_V4_PID " " TCP_V4_COMMAND "\n"
5380     TCP_V4_ADDRESS_" "
5381     TCP_V4_SWIND_" " TCP_V4_SNEXT_" " TCP_V4_SUNA_" "
5382     TCP_V4_RWIND_" " TCP_V4_RNEXT_" " TCP_V4_RACK_" "
5383     TCP_V4_RTO_" " TCP_V4_MSS_" " TCP_V4_STATE_" "
5384     TCP_V4_USER_" " TCP_V4_PID_" " TCP_V4_COMMAND_"\n";
5385 
5386 #define	TCP_V6_LOCAL		"   Local Address                 "
5387 #define	TCP_V6_LOCAL_		"---------------------------------"
5388 #define	TCP_V6_LOCAL_F		"%-33s"
5389 #define	TCP_V6_REMOTE		"   Remote Address                "
5390 #define	TCP_V6_REMOTE_		"---------------------------------"
5391 #define	TCP_V6_REMOTE_F		"%-33s"
5392 #define	TCP_V6_ADDRESS		"Local/Remote Address             "
5393 #define	TCP_V6_ADDRESS_		"---------------------------------"
5394 #define	TCP_V6_ADDRESS_F	"%-33s"
5395 #define	TCP_V6_IF		"  If "
5396 #define	TCP_V6_IF_		"-----"
5397 #define	TCP_V6_IF_F		"%-5.5s"
5398 #define	TCP_V6_SWIND		TCP_V4_SWIND
5399 #define	TCP_V6_SWIND_		TCP_V4_SWIND_
5400 #define	TCP_V6_SWIND_F		TCP_V4_SWIND_F
5401 #define	TCP_V6_SENDQ		TCP_V4_SENDQ
5402 #define	TCP_V6_SENDQ_		TCP_V4_SENDQ_
5403 #define	TCP_V6_SENDQ_F		TCP_V4_SENDQ_F
5404 #define	TCP_V6_RWIND		TCP_V4_RWIND
5405 #define	TCP_V6_RWIND_		TCP_V4_RWIND_
5406 #define	TCP_V6_RWIND_F		TCP_V4_RWIND_F
5407 #define	TCP_V6_RECVQ		TCP_V4_RECVQ
5408 #define	TCP_V6_RECVQ_		TCP_V4_RECVQ_
5409 #define	TCP_V6_RECVQ_F		TCP_V4_RECVQ_F
5410 #define	TCP_V6_SNEXT		TCP_V4_SNEXT
5411 #define	TCP_V6_SNEXT_		TCP_V4_SNEXT_
5412 #define	TCP_V6_SNEXT_F		TCP_V4_SNEXT_F
5413 #define	TCP_V6_SUNA		TCP_V4_SUNA
5414 #define	TCP_V6_SUNA_		TCP_V4_SUNA_
5415 #define	TCP_V6_SUNA_F		TCP_V4_SUNA_F
5416 #define	TCP_V6_RNEXT		TCP_V4_RNEXT
5417 #define	TCP_V6_RNEXT_		TCP_V4_RNEXT_
5418 #define	TCP_V6_RNEXT_F		TCP_V4_RNEXT_F
5419 #define	TCP_V6_RACK		TCP_V4_RACK
5420 #define	TCP_V6_RACK_		TCP_V4_RACK_
5421 #define	TCP_V6_RACK_F		TCP_V4_RACK_F
5422 #define	TCP_V6_RTO		TCP_V4_RTO
5423 #define	TCP_V6_RTO_		TCP_V4_RTO_
5424 #define	TCP_V6_RTO_F		TCP_V4_RTO_F
5425 #define	TCP_V6_MSS		TCP_V4_MSS
5426 #define	TCP_V6_MSS_		TCP_V4_MSS_
5427 #define	TCP_V6_MSS_F		TCP_V4_MSS_F
5428 #define	TCP_V6_STATE		TCP_V4_STATE
5429 #define	TCP_V6_STATE_		TCP_V4_STATE_
5430 #define	TCP_V6_STATE_F		TCP_V4_STATE_F
5431 #define	TCP_V6_USER		TCP_V4_USER
5432 #define	TCP_V6_USER_		TCP_V4_USER_
5433 #define	TCP_V6_USER_F		TCP_V4_USER_F
5434 #define	TCP_V6_PID		TCP_V4_PID
5435 #define	TCP_V6_PID_		TCP_V4_PID_
5436 #define	TCP_V6_PID_F		TCP_V4_PID_F
5437 #define	TCP_V6_COMMAND		TCP_V4_COMMAND
5438 #define	TCP_V6_COMMAND_		TCP_V4_COMMAND_
5439 #define	TCP_V6_COMMAND_F	TCP_V4_COMMAND_F
5440 
5441 static const char tcp_hdr_v6[] =
5442 "\nTCP: IPv6\n";
5443 static const char tcp_hdr_v6_normal[] =
5444     TCP_V6_LOCAL " " TCP_V6_REMOTE " "
5445     TCP_V6_SWIND " " TCP_V6_SENDQ " " TCP_V6_RWIND " " TCP_V6_RECVQ " "
5446     TCP_V6_STATE " " TCP_V6_IF "\n"
5447     TCP_V6_LOCAL_" " TCP_V6_REMOTE_" "
5448     TCP_V6_SWIND_" " TCP_V6_SENDQ_" " TCP_V6_RWIND_" " TCP_V6_RECVQ_" "
5449     TCP_V6_STATE_" " TCP_V6_IF_"\n";
5450 static const char tcp_hdr_v6_normal_pid[] =
5451     TCP_V6_LOCAL " " TCP_V6_REMOTE " "
5452     TCP_V6_USER " " TCP_V6_PID " " TCP_V6_COMMAND " "
5453     TCP_V6_SWIND " " TCP_V6_SENDQ " " TCP_V6_RWIND " " TCP_V6_RECVQ " "
5454     TCP_V6_STATE " " TCP_V6_IF "\n"
5455     TCP_V6_LOCAL_" " TCP_V6_REMOTE_" "
5456     TCP_V6_USER_" " TCP_V6_PID_" " TCP_V6_COMMAND_" "
5457     TCP_V6_SWIND_" " TCP_V6_SENDQ_" " TCP_V6_RWIND_" " TCP_V6_RECVQ_" "
5458     TCP_V6_STATE_" " TCP_V6_IF_"\n";
5459 static const char tcp_hdr_v6_verbose[] =
5460     TCP_V6_ADDRESS " "
5461     TCP_V6_SWIND " " TCP_V6_SNEXT " " TCP_V6_SUNA " "
5462     TCP_V6_RWIND " " TCP_V6_RNEXT " " TCP_V6_RACK " "
5463     TCP_V6_RTO " " TCP_V6_MSS " " TCP_V6_STATE " " TCP_V6_IF "\n"
5464     TCP_V6_ADDRESS_" "
5465     TCP_V6_SWIND_" " TCP_V6_SNEXT_" " TCP_V6_SUNA_" "
5466     TCP_V6_RWIND_" " TCP_V6_RNEXT_" " TCP_V6_RACK_" "
5467     TCP_V6_RTO_" " TCP_V6_MSS_" " TCP_V6_STATE_" " TCP_V6_IF_"\n";
5468 static const char tcp_hdr_v6_verbose_pid[] =
5469     TCP_V6_ADDRESS " "
5470     TCP_V6_SWIND " " TCP_V6_SNEXT " " TCP_V6_SUNA " "
5471     TCP_V6_RWIND " " TCP_V6_RNEXT " " TCP_V6_RACK " "
5472     TCP_V6_RTO " " TCP_V6_MSS " " TCP_V6_STATE " " TCP_V6_IF " "
5473     TCP_V6_USER " " TCP_V6_PID " " TCP_V6_COMMAND "\n"
5474     TCP_V6_ADDRESS_" "
5475     TCP_V6_SWIND_" " TCP_V6_SNEXT_" " TCP_V6_SUNA_" "
5476     TCP_V6_RWIND_" " TCP_V6_RNEXT_" " TCP_V6_RACK_" "
5477     TCP_V6_RTO_" " TCP_V6_MSS_" " TCP_V6_STATE_" " TCP_V6_IF_" "
5478     TCP_V6_USER_" " TCP_V6_PID_" " TCP_V6_COMMAND_"\n";
5479 
5480 static boolean_t tcp_report_item_v4(const mib2_tcpConnEntry_t *,
5481     boolean_t first, const mib2_transportMLPEntry_t *,
5482     const mib2_socketInfoEntry_t *);
5483 static boolean_t tcp_report_item_v6(const mib2_tcp6ConnEntry_t *,
5484     boolean_t first, const mib2_transportMLPEntry_t *,
5485     const mib2_socketInfoEntry_t *);
5486 
5487 static void
5488 tcp_report(const mib_item_t *item)
5489 {
5490 	int				jtemp = 0;
5491 	boolean_t			print_hdr_once_v4 = B_TRUE;
5492 	boolean_t			print_hdr_once_v6 = B_TRUE;
5493 	mib2_tcpConnEntry_t		*tp;
5494 	mib2_tcp6ConnEntry_t		*tp6;
5495 	mib2_transportMLPEntry_t	**v4_attrs, **v6_attrs, **v4a, **v6a;
5496 	mib2_transportMLPEntry_t	*aptr;
5497 	mib2_socketInfoEntry_t		**v4_info, **v6_info, **v4i, **v6i;
5498 	mib2_socketInfoEntry_t		*iptr;
5499 
5500 	if (!protocol_selected(IPPROTO_TCP))
5501 		return;
5502 
5503 	/*
5504 	 * Preparation pass: the kernel returns separate entries for TCP
5505 	 * connection table entries, Multilevel Port attributes and extra
5506 	 * socket information.  We loop through the attributes first and set up
5507 	 * an array for each address family.
5508 	 */
5509 	v4_attrs = family_selected(AF_INET) && RSECflag ?
5510 	    gather_attrs(item, MIB2_TCP, MIB2_TCP_CONN, tcpConnEntrySize) :
5511 	    NULL;
5512 	v6_attrs = family_selected(AF_INET6) && RSECflag ?
5513 	    gather_attrs(item, MIB2_TCP6, MIB2_TCP6_CONN, tcp6ConnEntrySize) :
5514 	    NULL;
5515 
5516 	v4_info = Uflag && family_selected(AF_INET) ?
5517 	    gather_info(item, MIB2_TCP, MIB2_TCP_CONN, tcpConnEntrySize) :
5518 	    NULL;
5519 	v6_info = Uflag && family_selected(AF_INET6) ?
5520 	    gather_info(item, MIB2_TCP6, MIB2_TCP6_CONN, tcp6ConnEntrySize) :
5521 	    NULL;
5522 
5523 	v4a = v4_attrs;
5524 	v6a = v6_attrs;
5525 	v4i = v4_info;
5526 	v6i = v6_info;
5527 	for (; item != NULL; item = item->next_item) {
5528 		if (Xflag) {
5529 			(void) printf("[%4d] Group = %d, mib_id = %d, "
5530 			    "length = %d, valp = 0x%p\n", jtemp++,
5531 			    item->group, item->mib_id,
5532 			    item->length, item->valp);
5533 		}
5534 
5535 		if (!((item->group == MIB2_TCP &&
5536 		    item->mib_id == MIB2_TCP_CONN) ||
5537 		    (item->group == MIB2_TCP6 &&
5538 		    item->mib_id == MIB2_TCP6_CONN)))
5539 			continue;
5540 
5541 		if (item->group == MIB2_TCP && !family_selected(AF_INET))
5542 			continue;
5543 		if (item->group == MIB2_TCP6 && !family_selected(AF_INET6))
5544 			continue;
5545 
5546 		if (item->group == MIB2_TCP) {
5547 			for (tp = (mib2_tcpConnEntry_t *)item->valp;
5548 			    (char *)tp < (char *)item->valp + item->length;
5549 			    tp = (mib2_tcpConnEntry_t *)((char *)tp +
5550 			    tcpConnEntrySize)) {
5551 				aptr = v4a == NULL ? NULL : *v4a++;
5552 				iptr = v4i == NULL ? NULL : *v4i++;
5553 				print_hdr_once_v4 = tcp_report_item_v4(tp,
5554 				    print_hdr_once_v4, aptr, iptr);
5555 			}
5556 		} else {
5557 			for (tp6 = (mib2_tcp6ConnEntry_t *)item->valp;
5558 			    (char *)tp6 < (char *)item->valp + item->length;
5559 			    tp6 = (mib2_tcp6ConnEntry_t *)((char *)tp6 +
5560 			    tcp6ConnEntrySize)) {
5561 				aptr = v6a == NULL ? NULL : *v6a++;
5562 				iptr = v6i == NULL ? NULL : *v6i++;
5563 				print_hdr_once_v6 = tcp_report_item_v6(tp6,
5564 				    print_hdr_once_v6, aptr, iptr);
5565 			}
5566 		}
5567 	}
5568 	(void) fflush(stdout);
5569 
5570 	free(v4_attrs);
5571 	free(v6_attrs);
5572 	free(v4_info);
5573 	free(v6_info);
5574 }
5575 
5576 static boolean_t
5577 tcp_report_item_v4(const mib2_tcpConnEntry_t *tp, boolean_t first,
5578     const mib2_transportMLPEntry_t *attr, const mib2_socketInfoEntry_t *sie)
5579 {
5580 	/*
5581 	 * lname and fname below are for the hostname as well as the portname
5582 	 * There is no limit on portname length so we assume MAXHOSTNAMELEN
5583 	 * as the limit
5584 	 */
5585 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5586 	char	fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5587 	proc_fdinfo_t	*ph;
5588 
5589 	if (!(Aflag || tp->tcpConnEntryInfo.ce_state >= TCPS_ESTABLISHED))
5590 		return (first); /* Nothing to print */
5591 
5592 	if (first) {
5593 		(void) printf(v4compat ? tcp_hdr_v4_compat : tcp_hdr_v4);
5594 		if (Vflag)
5595 			(void) printf(Uflag ? tcp_hdr_v4_verbose_pid :
5596 			    tcp_hdr_v4_verbose);
5597 		else
5598 			(void) printf(Uflag ? tcp_hdr_v4_normal_pid :
5599 			    tcp_hdr_v4_normal);
5600 	}
5601 
5602 	int64_t sq = (int64_t)tp->tcpConnEntryInfo.ce_snxt -
5603 	    (int64_t)tp->tcpConnEntryInfo.ce_suna - 1;
5604 	int64_t rq = (int64_t)tp->tcpConnEntryInfo.ce_rnxt -
5605 	    (int64_t)tp->tcpConnEntryInfo.ce_rack;
5606 
5607 	if (Xflag)
5608 		sie_report(sie);
5609 
5610 	if (Uflag) {
5611 		ph = process_hash_get(sie, SOCK_STREAM, AF_INET);
5612 		if (ph->ph_pid == 0 && sie != NULL &&
5613 		    (sie->sie_flags & MIB2_SOCKINFO_IPV6)) {
5614 			ph = process_hash_get(sie, SOCK_STREAM, AF_INET6);
5615 		}
5616 	}
5617 
5618 	if (!Uflag && Vflag) {
5619 		(void) printf(
5620 		    TCP_V4_LOCAL_F "\n" TCP_V4_REMOTE_F " "
5621 		    TCP_V4_SWIND_F " " TCP_V4_SNEXT_F " "
5622 		    TCP_V4_SUNA_F " " TCP_V4_RWIND_F " "
5623 		    TCP_V4_RNEXT_F " " TCP_V4_RACK_F " "
5624 		    TCP_V4_RTO_F " " TCP_V4_MSS_F " %s\n",
5625 		    pr_ap(tp->tcpConnLocalAddress,
5626 		    tp->tcpConnLocalPort, "tcp", lname, sizeof (lname)),
5627 		    pr_ap(tp->tcpConnRemAddress,
5628 		    tp->tcpConnRemPort, "tcp", fname, sizeof (fname)),
5629 		    tp->tcpConnEntryInfo.ce_swnd,
5630 		    tp->tcpConnEntryInfo.ce_snxt,
5631 		    tp->tcpConnEntryInfo.ce_suna,
5632 		    tp->tcpConnEntryInfo.ce_rwnd,
5633 		    tp->tcpConnEntryInfo.ce_rnxt,
5634 		    tp->tcpConnEntryInfo.ce_rack,
5635 		    tp->tcpConnEntryInfo.ce_rto,
5636 		    tp->tcpConnEntryInfo.ce_mss,
5637 		    mitcp_state(tp->tcpConnEntryInfo.ce_state, attr));
5638 	} else if (!Uflag) {
5639 		(void) printf(
5640 		    TCP_V4_LOCAL_F " " TCP_V4_REMOTE_F " "
5641 		    TCP_V4_SWIND_F " " TCP_V4_SENDQ_F " "
5642 		    TCP_V4_RWIND_F " " TCP_V4_RECVQ_F " %s\n",
5643 		    pr_ap(tp->tcpConnLocalAddress,
5644 		    tp->tcpConnLocalPort, "tcp", lname, sizeof (lname)),
5645 		    pr_ap(tp->tcpConnRemAddress,
5646 		    tp->tcpConnRemPort, "tcp", fname, sizeof (fname)),
5647 		    tp->tcpConnEntryInfo.ce_swnd,
5648 		    (sq >= 0) ? sq : 0,
5649 		    tp->tcpConnEntryInfo.ce_rwnd,
5650 		    (rq >= 0) ? rq : 0,
5651 		    mitcp_state(tp->tcpConnEntryInfo.ce_state, attr));
5652 	} else if (Uflag && Vflag) {
5653 		for (; ph != NULL; ph = ph->ph_next_proc) {
5654 			(void) printf(
5655 			    TCP_V4_LOCAL_F "\n" TCP_V4_REMOTE_F " "
5656 			    TCP_V4_SWIND_F " " TCP_V4_SNEXT_F " "
5657 			    TCP_V4_SUNA_F " " TCP_V4_RWIND_F " "
5658 			    TCP_V4_RNEXT_F " " TCP_V4_RACK_F " "
5659 			    TCP_V4_RTO_F " " TCP_V4_MSS_F " "
5660 			    TCP_V4_STATE_F " " TCP_V4_USER_F " "
5661 			    TCP_V4_PID_F " %s\n",
5662 			    pr_ap(tp->tcpConnLocalAddress,
5663 			    tp->tcpConnLocalPort, "tcp", lname, sizeof (lname)),
5664 			    pr_ap(tp->tcpConnRemAddress,
5665 			    tp->tcpConnRemPort, "tcp", fname, sizeof (fname)),
5666 			    tp->tcpConnEntryInfo.ce_swnd,
5667 			    tp->tcpConnEntryInfo.ce_snxt,
5668 			    tp->tcpConnEntryInfo.ce_suna,
5669 			    tp->tcpConnEntryInfo.ce_rwnd,
5670 			    tp->tcpConnEntryInfo.ce_rnxt,
5671 			    tp->tcpConnEntryInfo.ce_rack,
5672 			    tp->tcpConnEntryInfo.ce_rto,
5673 			    tp->tcpConnEntryInfo.ce_mss,
5674 			    mitcp_state(tp->tcpConnEntryInfo.ce_state, attr),
5675 			    ph->ph_username, ph->ph_pidstr, ph->ph_psargs);
5676 		}
5677 	} else if (Uflag) {
5678 		for (; ph != NULL; ph = ph->ph_next_proc) {
5679 			(void) printf(
5680 			    TCP_V4_LOCAL_F " " TCP_V4_REMOTE_F " "
5681 			    TCP_V4_USER_F " "TCP_V4_PID_F " "
5682 			    TCP_V4_COMMAND_F " "
5683 			    TCP_V4_SWIND_F " " TCP_V4_SENDQ_F " "
5684 			    TCP_V4_RWIND_F " " TCP_V4_RECVQ_F " %s\n",
5685 			    pr_ap(tp->tcpConnLocalAddress,
5686 			    tp->tcpConnLocalPort, "tcp", lname, sizeof (lname)),
5687 			    pr_ap(tp->tcpConnRemAddress,
5688 			    tp->tcpConnRemPort, "tcp", fname, sizeof (fname)),
5689 			    ph->ph_username, ph->ph_pidstr, ph->ph_fname,
5690 			    tp->tcpConnEntryInfo.ce_swnd,
5691 			    (sq >= 0) ? sq : 0,
5692 			    tp->tcpConnEntryInfo.ce_rwnd,
5693 			    (rq >= 0) ? rq : 0,
5694 			    mitcp_state(tp->tcpConnEntryInfo.ce_state, attr));
5695 		}
5696 	}
5697 
5698 	print_transport_label(attr);
5699 
5700 	return (B_FALSE);
5701 }
5702 
5703 static boolean_t
5704 tcp_report_item_v6(const mib2_tcp6ConnEntry_t *tp6, boolean_t first,
5705     const mib2_transportMLPEntry_t *attr, const mib2_socketInfoEntry_t *sie)
5706 {
5707 	/*
5708 	 * lname and fname below are for the hostname as well as the portname
5709 	 * There is no limit on portname length so we assume MAXHOSTNAMELEN
5710 	 * as the limit
5711 	 */
5712 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5713 	char	fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
5714 	char	ifname[LIFNAMSIZ + 1];
5715 	char	*ifnamep;
5716 	proc_fdinfo_t	*ph;
5717 
5718 	if (!(Aflag || tp6->tcp6ConnEntryInfo.ce_state >= TCPS_ESTABLISHED))
5719 		return (first); /* Nothing to print */
5720 
5721 	if (first) {
5722 		(void) printf(tcp_hdr_v6);
5723 		if (Vflag)
5724 			(void) printf(Uflag ? tcp_hdr_v6_verbose_pid :
5725 			    tcp_hdr_v6_verbose);
5726 		else
5727 			(void) printf(Uflag ? tcp_hdr_v6_normal_pid :
5728 			    tcp_hdr_v6_normal);
5729 	}
5730 
5731 	ifnamep = (tp6->tcp6ConnIfIndex != 0) ?
5732 	    if_indextoname(tp6->tcp6ConnIfIndex, ifname) : NULL;
5733 	if (ifnamep == NULL)
5734 		ifnamep = "";
5735 
5736 	int64_t sq = (int64_t)tp6->tcp6ConnEntryInfo.ce_snxt -
5737 	    (int64_t)tp6->tcp6ConnEntryInfo.ce_suna - 1;
5738 	int64_t rq = (int64_t)tp6->tcp6ConnEntryInfo.ce_rnxt -
5739 	    (int64_t)tp6->tcp6ConnEntryInfo.ce_rack;
5740 
5741 	if (Xflag)
5742 		sie_report(sie);
5743 
5744 	if (!Uflag && Vflag) {
5745 		(void) printf(
5746 		    TCP_V6_LOCAL_F "\n" TCP_V6_REMOTE_F " "
5747 		    TCP_V6_SWIND_F " " TCP_V6_SNEXT_F " "
5748 		    TCP_V6_SUNA_F " " TCP_V6_RWIND_F " "
5749 		    TCP_V6_RNEXT_F " " TCP_V6_RACK_F " "
5750 		    TCP_V6_RTO_F " " TCP_V6_MSS_F " "
5751 		    TCP_V6_STATE_F " %s\n",
5752 		    pr_ap6(&tp6->tcp6ConnLocalAddress,
5753 		    tp6->tcp6ConnLocalPort, "tcp", lname, sizeof (lname)),
5754 		    pr_ap6(&tp6->tcp6ConnRemAddress,
5755 		    tp6->tcp6ConnRemPort, "tcp", fname, sizeof (fname)),
5756 		    tp6->tcp6ConnEntryInfo.ce_swnd,
5757 		    tp6->tcp6ConnEntryInfo.ce_snxt,
5758 		    tp6->tcp6ConnEntryInfo.ce_suna,
5759 		    tp6->tcp6ConnEntryInfo.ce_rwnd,
5760 		    tp6->tcp6ConnEntryInfo.ce_rnxt,
5761 		    tp6->tcp6ConnEntryInfo.ce_rack,
5762 		    tp6->tcp6ConnEntryInfo.ce_rto,
5763 		    tp6->tcp6ConnEntryInfo.ce_mss,
5764 		    mitcp_state(tp6->tcp6ConnEntryInfo.ce_state, attr),
5765 		    ifnamep);
5766 	} else if (!Uflag) {
5767 		(void) printf(
5768 		    TCP_V6_LOCAL_F " " TCP_V6_REMOTE_F " "
5769 		    TCP_V6_SWIND_F " " TCP_V6_SENDQ_F " "
5770 		    TCP_V6_RWIND_F " " TCP_V6_RECVQ_F " "
5771 		    TCP_V6_STATE_F " %s\n",
5772 		    pr_ap6(&tp6->tcp6ConnLocalAddress,
5773 		    tp6->tcp6ConnLocalPort, "tcp", lname, sizeof (lname)),
5774 		    pr_ap6(&tp6->tcp6ConnRemAddress,
5775 		    tp6->tcp6ConnRemPort, "tcp", fname, sizeof (fname)),
5776 		    tp6->tcp6ConnEntryInfo.ce_swnd,
5777 		    (sq >= 0) ? sq : 0,
5778 		    tp6->tcp6ConnEntryInfo.ce_rwnd,
5779 		    (rq >= 0) ? rq : 0,
5780 		    mitcp_state(tp6->tcp6ConnEntryInfo.ce_state, attr),
5781 		    ifnamep);
5782 	} else if (Uflag && Vflag) {
5783 		for (ph = process_hash_get(sie, SOCK_STREAM, AF_INET6);
5784 		    ph != NULL; ph = ph->ph_next_proc) {
5785 			(void) printf(
5786 			    TCP_V6_LOCAL_F "\n" TCP_V6_REMOTE_F " "
5787 			    TCP_V6_SWIND_F " " TCP_V6_SNEXT_F " "
5788 			    TCP_V6_SUNA_F " " TCP_V6_RWIND_F " "
5789 			    TCP_V6_RNEXT_F " " TCP_V6_RACK_F " "
5790 			    TCP_V6_RTO_F " " TCP_V6_MSS_F " "
5791 			    TCP_V6_STATE_F " " TCP_V6_IF_F " "
5792 			    TCP_V6_USER_F " " TCP_V6_PID_F " %s\n",
5793 			    pr_ap6(&tp6->tcp6ConnLocalAddress,
5794 			    tp6->tcp6ConnLocalPort, "tcp", lname,
5795 			    sizeof (lname)),
5796 			    pr_ap6(&tp6->tcp6ConnRemAddress,
5797 			    tp6->tcp6ConnRemPort, "tcp", fname,
5798 			    sizeof (fname)),
5799 			    tp6->tcp6ConnEntryInfo.ce_swnd,
5800 			    tp6->tcp6ConnEntryInfo.ce_snxt,
5801 			    tp6->tcp6ConnEntryInfo.ce_suna,
5802 			    tp6->tcp6ConnEntryInfo.ce_rwnd,
5803 			    tp6->tcp6ConnEntryInfo.ce_rnxt,
5804 			    tp6->tcp6ConnEntryInfo.ce_rack,
5805 			    tp6->tcp6ConnEntryInfo.ce_rto,
5806 			    tp6->tcp6ConnEntryInfo.ce_mss,
5807 			    mitcp_state(tp6->tcp6ConnEntryInfo.ce_state, attr),
5808 			    ifnamep,
5809 			    ph->ph_username, ph->ph_pidstr, ph->ph_psargs);
5810 		}
5811 	} else if (Uflag) {
5812 		for (ph = process_hash_get(sie, SOCK_STREAM, AF_INET6);
5813 		    ph != NULL; ph = ph->ph_next_proc) {
5814 			(void) printf(
5815 			    TCP_V6_LOCAL_F " " TCP_V6_REMOTE_F " "
5816 			    TCP_V6_USER_F " " TCP_V6_PID_F " "
5817 			    TCP_V6_COMMAND_F " "
5818 			    TCP_V6_SWIND_F " " TCP_V6_SENDQ_F " "
5819 			    TCP_V6_RWIND_F " " TCP_V6_RECVQ_F " "
5820 			    TCP_V6_STATE_F " %s\n",
5821 			    pr_ap6(&tp6->tcp6ConnLocalAddress,
5822 			    tp6->tcp6ConnLocalPort, "tcp", lname,
5823 			    sizeof (lname)),
5824 			    pr_ap6(&tp6->tcp6ConnRemAddress,
5825 			    tp6->tcp6ConnRemPort, "tcp", fname, sizeof (fname)),
5826 			    ph->ph_username, ph->ph_pidstr, ph->ph_fname,
5827 			    tp6->tcp6ConnEntryInfo.ce_swnd,
5828 			    (sq >= 0) ? sq : 0,
5829 			    tp6->tcp6ConnEntryInfo.ce_rwnd,
5830 			    (rq >= 0) ? rq : 0,
5831 			    mitcp_state(tp6->tcp6ConnEntryInfo.ce_state, attr),
5832 			    ifnamep);
5833 		}
5834 	}
5835 
5836 	print_transport_label(attr);
5837 
5838 	return (B_FALSE);
5839 }
5840 
5841 /* ------------------------------- UDP_REPORT------------------------------- */
5842 
5843 static boolean_t udp_report_item_v4(const mib2_udpEntry_t *, boolean_t,
5844     const mib2_transportMLPEntry_t *, const mib2_socketInfoEntry_t *);
5845 static boolean_t udp_report_item_v6(const mib2_udp6Entry_t *, boolean_t,
5846     const mib2_transportMLPEntry_t *, const mib2_socketInfoEntry_t *);
5847 
5848 /*
5849  * Central definitions for the columns used in the reports.
5850  * For each column, there's a definition for the heading, the underline and
5851  * the formatted value.
5852  * Since most reports select different columns depending on command line
5853  * options, defining everything here avoids duplication in the report
5854  * format strings and makes it easy to make changes as necessary.
5855  */
5856 #define	UDP_V4_LOCAL		"   Local Address    "
5857 #define	UDP_V4_LOCAL_		"--------------------"
5858 #define	UDP_V4_LOCAL_F		"%-20s"
5859 #define	UDP_V4_REMOTE		"   Remote Address   "
5860 #define	UDP_V4_REMOTE_		"--------------------"
5861 #define	UDP_V4_REMOTE_F		"%-20s"
5862 #define	UDP_V4_STATE		"  State   "
5863 #define	UDP_V4_STATE_		"----------"
5864 #define	UDP_V4_STATE_F		"%-10.10s"
5865 #define	UDP_V4_USER		"  User  "
5866 #define	UDP_V4_USER_		"--------"
5867 #define	UDP_V4_USER_F		"%-8.8s"
5868 #define	UDP_V4_PID		" Pid  "
5869 #define	UDP_V4_PID_		"------"
5870 #define	UDP_V4_PID_F		"%6s"
5871 #define	UDP_V4_COMMAND		"   Command    "
5872 #define	UDP_V4_COMMAND_		"--------------"
5873 #define	UDP_V4_COMMAND_F	"%-14.14s"
5874 
5875 static const char udp_hdr_v4[] =
5876     UDP_V4_LOCAL " " UDP_V4_REMOTE " " UDP_V4_STATE "\n"
5877     UDP_V4_LOCAL_" " UDP_V4_REMOTE_" " UDP_V4_STATE_"\n";
5878 
5879 static const char udp_hdr_v4_pid[] =
5880     UDP_V4_LOCAL " " UDP_V4_REMOTE " "
5881     UDP_V4_USER " " UDP_V4_PID " " UDP_V4_COMMAND " " UDP_V4_STATE "\n"
5882     UDP_V4_LOCAL_" " UDP_V4_REMOTE_" "
5883     UDP_V4_USER_" " UDP_V4_PID_" " UDP_V4_COMMAND_" " UDP_V4_STATE_"\n";
5884 static const char udp_hdr_v4_pid_verbose[] =
5885     UDP_V4_LOCAL " " UDP_V4_REMOTE " "
5886     UDP_V4_USER " " UDP_V4_PID " " UDP_V4_STATE " " UDP_V4_COMMAND "\n"
5887     UDP_V4_LOCAL_" " UDP_V4_REMOTE_" "
5888     UDP_V4_USER_" " UDP_V4_PID_" " UDP_V4_STATE_" " UDP_V4_COMMAND_"\n";
5889 
5890 #define	UDP_V6_LOCAL		"   Local Address                 "
5891 #define	UDP_V6_LOCAL_		"---------------------------------"
5892 #define	UDP_V6_LOCAL_F		"%-33s"
5893 #define	UDP_V6_REMOTE		"   Remote Address                "
5894 #define	UDP_V6_REMOTE_		"---------------------------------"
5895 #define	UDP_V6_REMOTE_F		"%-33s"
5896 #define	UDP_V6_STATE		UDP_V4_STATE
5897 #define	UDP_V6_STATE_		UDP_V4_STATE_
5898 #define	UDP_V6_STATE_F		UDP_V4_STATE_F
5899 #define	UDP_V6_USER		UDP_V4_USER
5900 #define	UDP_V6_USER_		UDP_V4_USER_
5901 #define	UDP_V6_USER_F		UDP_V4_USER_F
5902 #define	UDP_V6_PID		UDP_V4_PID
5903 #define	UDP_V6_PID_		UDP_V4_PID_
5904 #define	UDP_V6_PID_F		UDP_V4_PID_F
5905 #define	UDP_V6_COMMAND		UDP_V4_COMMAND
5906 #define	UDP_V6_COMMAND_		UDP_V4_COMMAND_
5907 #define	UDP_V6_COMMAND_F	UDP_V4_COMMAND_F
5908 #define	UDP_V6_IF		"  If "
5909 #define	UDP_V6_IF_		"-----"
5910 #define	UDP_V6_IF_F		"%-5.5s"
5911 
5912 static const char udp_hdr_v6[] =
5913     UDP_V6_LOCAL " " UDP_V6_REMOTE " " UDP_V6_STATE " "
5914     UDP_V6_IF "\n"
5915     UDP_V6_LOCAL_" " UDP_V6_REMOTE_" " UDP_V6_STATE_" "
5916     UDP_V6_IF_"\n";
5917 
5918 static const char udp_hdr_v6_pid[] =
5919     UDP_V6_LOCAL " " UDP_V6_REMOTE " "
5920     UDP_V6_USER " " UDP_V6_PID " " UDP_V6_COMMAND " "
5921     UDP_V6_STATE " " UDP_V6_IF "\n"
5922     UDP_V6_LOCAL_" " UDP_V6_REMOTE_" "
5923     UDP_V6_USER_" " UDP_V6_PID_" " UDP_V6_COMMAND_" "
5924     UDP_V6_STATE_" " UDP_V6_IF_"\n";
5925 
5926 static const char udp_hdr_v6_pid_verbose[] =
5927     UDP_V6_LOCAL " " UDP_V6_REMOTE " "
5928     UDP_V6_USER " " UDP_V6_PID " " UDP_V6_STATE " "
5929     UDP_V6_IF " " UDP_V6_COMMAND "\n"
5930     UDP_V6_LOCAL_" " UDP_V6_REMOTE_" "
5931     UDP_V6_USER_" " UDP_V6_PID_" " UDP_V6_STATE_" "
5932     UDP_V6_IF_" " UDP_V6_COMMAND_ "\n";
5933 
5934 static void
5935 udp_report(const mib_item_t *item)
5936 {
5937 	int				jtemp = 0;
5938 	boolean_t			print_hdr_once_v4 = B_TRUE;
5939 	boolean_t			print_hdr_once_v6 = B_TRUE;
5940 	mib2_udpEntry_t			*ude;
5941 	mib2_udp6Entry_t		*ude6;
5942 	mib2_transportMLPEntry_t	**v4_attrs, **v6_attrs, **v4a, **v6a;
5943 	mib2_transportMLPEntry_t	*aptr;
5944 	mib2_socketInfoEntry_t		**v4_info, **v6_info, **v4i, **v6i;
5945 	mib2_socketInfoEntry_t		*iptr;
5946 
5947 	if (!protocol_selected(IPPROTO_UDP))
5948 		return;
5949 
5950 	/*
5951 	 * Preparation pass: the kernel returns separate entries for UDP
5952 	 * connection table entries and Multilevel Port attributes.  We loop
5953 	 * through the attributes first and set up an array for each address
5954 	 * family.
5955 	 */
5956 	v4_attrs = family_selected(AF_INET) && RSECflag ?
5957 	    gather_attrs(item, MIB2_UDP, MIB2_UDP_ENTRY, udpEntrySize) : NULL;
5958 	v6_attrs = family_selected(AF_INET6) && RSECflag ?
5959 	    gather_attrs(item, MIB2_UDP6, MIB2_UDP6_ENTRY, udp6EntrySize) :
5960 	    NULL;
5961 
5962 	v4_info = Uflag && family_selected(AF_INET) ?
5963 	    gather_info(item, MIB2_UDP, MIB2_UDP_ENTRY, udpEntrySize) :
5964 	    NULL;
5965 	v6_info = Uflag && family_selected(AF_INET6) ?
5966 	    gather_info(item, MIB2_UDP6, MIB2_UDP6_ENTRY, udp6EntrySize) :
5967 	    NULL;
5968 
5969 	v4a = v4_attrs;
5970 	v6a = v6_attrs;
5971 	v4i = v4_info;
5972 	v6i = v6_info;
5973 	for (; item; item = item->next_item) {
5974 		if (Xflag) {
5975 			(void) printf("[%4d] Group = %d, mib_id = %d, "
5976 			    "length = %d, valp = 0x%p\n", jtemp++,
5977 			    item->group, item->mib_id,
5978 			    item->length, item->valp);
5979 		}
5980 		if (!((item->group == MIB2_UDP &&
5981 		    item->mib_id == MIB2_UDP_ENTRY) ||
5982 		    (item->group == MIB2_UDP6 &&
5983 		    item->mib_id == MIB2_UDP6_ENTRY)))
5984 			continue;
5985 
5986 		if (item->group == MIB2_UDP && !family_selected(AF_INET))
5987 			continue;
5988 		else if (item->group == MIB2_UDP6 && !family_selected(AF_INET6))
5989 			continue;
5990 
5991 		if (item->group == MIB2_UDP) {
5992 			for (ude = (mib2_udpEntry_t *)item->valp;
5993 			    (char *)ude < (char *)item->valp + item->length;
5994 			    ude = (mib2_udpEntry_t *)((char *)ude +
5995 			    udpEntrySize)) {
5996 				aptr = v4a == NULL ? NULL : *v4a++;
5997 				iptr = v4i == NULL ? NULL : *v4i++;
5998 				print_hdr_once_v4 = udp_report_item_v4(ude,
5999 				    print_hdr_once_v4, aptr, iptr);
6000 			}
6001 		} else {
6002 			for (ude6 = (mib2_udp6Entry_t *)item->valp;
6003 			    (char *)ude6 < (char *)item->valp + item->length;
6004 			    ude6 = (mib2_udp6Entry_t *)((char *)ude6 +
6005 			    udp6EntrySize)) {
6006 				aptr = v6a == NULL ? NULL : *v6a++;
6007 				iptr = v6i == NULL ? NULL : *v6i++;
6008 				print_hdr_once_v6 = udp_report_item_v6(ude6,
6009 				    print_hdr_once_v6, aptr, iptr);
6010 			}
6011 		}
6012 
6013 	}
6014 	(void) fflush(stdout);
6015 
6016 	free(v4_attrs);
6017 	free(v6_attrs);
6018 	free(v4_info);
6019 	free(v6_info);
6020 }
6021 
6022 static boolean_t
6023 udp_report_item_v4(const mib2_udpEntry_t *ude, boolean_t first,
6024     const mib2_transportMLPEntry_t *attr, const mib2_socketInfoEntry_t *sie)
6025 {
6026 	char	*leadin;
6027 	char	lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
6028 			/* hostname + portname */
6029 	proc_fdinfo_t	*ph;
6030 
6031 	if (!(Aflag || ude->udpEntryInfo.ue_state >= MIB2_UDP_connected))
6032 		return (first); /* Nothing to print */
6033 
6034 	if (first) {
6035 		(void) printf(v4compat ? "\nUDP\n" : "\nUDP: IPv4\n");
6036 
6037 		if (Uflag)
6038 			(void) printf(Vflag ? udp_hdr_v4_pid_verbose :
6039 			    udp_hdr_v4_pid);
6040 		else
6041 			(void) printf(udp_hdr_v4);
6042 
6043 		first = B_FALSE;
6044 	}
6045 
6046 	if (Xflag)
6047 		sie_report(sie);
6048 
6049 	if (asprintf(&leadin,
6050 	    UDP_V4_LOCAL_F " " UDP_V4_REMOTE_F " ",
6051 	    pr_ap(ude->udpLocalAddress, ude->udpLocalPort, "udp",
6052 	    lname, sizeof (lname)),
6053 	    ude->udpEntryInfo.ue_state == MIB2_UDP_connected ?
6054 	    pr_ap(ude->udpEntryInfo.ue_RemoteAddress,
6055 	    ude->udpEntryInfo.ue_RemotePort, "udp", lname, sizeof (lname)) :
6056 	    "") == -1) {
6057 		fatal(1, "Out of memory");
6058 	}
6059 	if (!Uflag) {
6060 		(void) printf("%s%s\n",
6061 		    leadin, miudp_state(ude->udpEntryInfo.ue_state, attr));
6062 	} else {
6063 		ph = process_hash_get(sie, SOCK_DGRAM, AF_INET);
6064 		if (ph->ph_pid == 0 && sie != NULL &&
6065 		    (sie->sie_flags & MIB2_SOCKINFO_IPV6))
6066 			ph = process_hash_get(sie, SOCK_DGRAM, AF_INET6);
6067 		for (; ph != NULL; ph = ph->ph_next_proc) {
6068 			(void) printf("%s" UDP_V4_USER_F " " UDP_V4_PID_F " ",
6069 			    leadin, ph->ph_username, ph->ph_pidstr);
6070 			if (Vflag) {
6071 				(void) printf(UDP_V4_STATE_F " %s\n",
6072 				    miudp_state(ude->udpEntryInfo.ue_state,
6073 				    attr),
6074 				    ph->ph_psargs);
6075 			} else {
6076 				(void) printf(UDP_V4_COMMAND_F " %s\n",
6077 				    ph->ph_fname,
6078 				    miudp_state(ude->udpEntryInfo.ue_state,
6079 				    attr));
6080 			}
6081 		}
6082 	}
6083 
6084 	print_transport_label(attr);
6085 
6086 	free(leadin);
6087 
6088 	return (first);
6089 }
6090 
6091 static boolean_t
6092 udp_report_item_v6(const mib2_udp6Entry_t *ude6, boolean_t first,
6093     const mib2_transportMLPEntry_t *attr, const mib2_socketInfoEntry_t *sie)
6094 {
6095 	char		*leadin;
6096 	char		lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
6097 			/* hostname + portname */
6098 	char		ifname[LIFNAMSIZ + 1];
6099 	const char	*ifnamep;
6100 	proc_fdinfo_t	*ph;
6101 
6102 	if (!(Aflag || ude6->udp6EntryInfo.ue_state >= MIB2_UDP_connected))
6103 		return (first); /* Nothing to print */
6104 
6105 	if (first) {
6106 		(void) printf("\nUDP: IPv6\n");
6107 
6108 		if (Uflag)
6109 			(void) printf(Vflag ? udp_hdr_v6_pid_verbose :
6110 			    udp_hdr_v6_pid);
6111 		else
6112 			(void) printf(udp_hdr_v6);
6113 
6114 		first = B_FALSE;
6115 	}
6116 
6117 	ifnamep = (ude6->udp6IfIndex != 0) ?
6118 	    if_indextoname(ude6->udp6IfIndex, ifname) : NULL;
6119 
6120 	if (Xflag)
6121 		sie_report(sie);
6122 
6123 	if (asprintf(&leadin,
6124 	    UDP_V6_LOCAL_F " " UDP_V6_REMOTE_F " ",
6125 	    pr_ap6(&ude6->udp6LocalAddress,
6126 	    ude6->udp6LocalPort, "udp", lname, sizeof (lname)),
6127 	    ude6->udp6EntryInfo.ue_state == MIB2_UDP_connected ?
6128 	    pr_ap6(&ude6->udp6EntryInfo.ue_RemoteAddress,
6129 	    ude6->udp6EntryInfo.ue_RemotePort, "udp", lname, sizeof (lname)) :
6130 	    "") == -1) {
6131 		fatal(1, "Out of memory");
6132 	}
6133 	if (!Uflag) {
6134 		(void) printf("%s" UDP_V6_STATE_F " %s\n", leadin,
6135 		    miudp_state(ude6->udp6EntryInfo.ue_state, attr),
6136 		    ifnamep == NULL ? "" : ifnamep);
6137 	} else {
6138 		for (ph = process_hash_get(sie, SOCK_DGRAM, AF_INET6);
6139 		    ph != NULL; ph = ph->ph_next_proc) {
6140 			(void) printf("%s" UDP_V6_USER_F " " UDP_V6_PID_F " ",
6141 			    leadin, ph->ph_username, ph->ph_pidstr);
6142 			if (Vflag) {
6143 				(void) printf(
6144 				    UDP_V6_STATE_F " " UDP_V6_IF_F " %s\n",
6145 				    miudp_state(ude6->udp6EntryInfo.ue_state,
6146 				    attr),
6147 				    ifnamep == NULL ? "" : ifnamep,
6148 				    ph->ph_psargs);
6149 			} else {
6150 				(void) printf(
6151 				    UDP_V6_COMMAND_F " " UDP_V6_STATE_F " %s\n",
6152 				    ph->ph_fname,
6153 				    miudp_state(ude6->udp6EntryInfo.ue_state,
6154 				    attr),
6155 				    ifnamep == NULL ? "" : ifnamep);
6156 			}
6157 		}
6158 	}
6159 
6160 	print_transport_label(attr);
6161 
6162 	free(leadin);
6163 
6164 	return (first);
6165 }
6166 
6167 /* ------------------------------ SCTP_REPORT------------------------------- */
6168 
6169 /*
6170  * Central definitions for the columns used in the reports.
6171  * For each column, there's a definition for the heading, the underline and
6172  * the formatted value.
6173  * Since most reports select different columns depending on command line
6174  * options, defining everything here avoids duplication in the report
6175  * format strings and makes it easy to make changes as necessary.
6176  */
6177 #define	SCTP_LOCAL		"        Local Address          "
6178 #define	SCTP_LOCAL_		"-------------------------------"
6179 #define	SCTP_LOCAL_F		"%-31s"
6180 #define	SCTP_REMOTE		"        Remote Address         "
6181 #define	SCTP_REMOTE_		"-------------------------------"
6182 #define	SCTP_REMOTE_F		"%-31s"
6183 #define	SCTP_SWIND		"Swind "
6184 #define	SCTP_SWIND_		"------"
6185 #define	SCTP_SWIND_F		"%6u"
6186 #define	SCTP_SENDQ		"Send-Q"
6187 #define	SCTP_SENDQ_		"------"
6188 #define	SCTP_SENDQ_F		"%6d"
6189 #define	SCTP_RWIND		"Rwind "
6190 #define	SCTP_RWIND_		"------"
6191 #define	SCTP_RWIND_F		"%6d"
6192 #define	SCTP_RECVQ		"Recv-Q"
6193 #define	SCTP_RECVQ_		"------"
6194 #define	SCTP_RECVQ_F		"%6u"
6195 #define	SCTP_STRS		"StrsI/O"
6196 #define	SCTP_STRS_		"-------"
6197 #define	SCTP_STRS_FI		"%3d"
6198 #define	SCTP_STRS_FO		"%-3d"
6199 #define	SCTP_STATE		" State     "
6200 #define	SCTP_STATE_		"-----------"
6201 #define	SCTP_STATE_F		"%-11.11s"
6202 #define	SCTP_USER		"  User  "
6203 #define	SCTP_USER_		"--------"
6204 #define	SCTP_USER_F		"%-8.8s"
6205 #define	SCTP_PID		" Pid  "
6206 #define	SCTP_PID_		"------"
6207 #define	SCTP_PID_F		"%6s"
6208 #define	SCTP_COMMAND		"   Command    "
6209 #define	SCTP_COMMAND_		"--------------"
6210 #define	SCTP_COMMAND_F		"%-14.14s"
6211 
6212 static const char sctp_hdr[] =
6213 "\nSCTP:";
6214 static const char sctp_hdr_normal[] =
6215     SCTP_LOCAL " " SCTP_REMOTE " "
6216     SCTP_SWIND " " SCTP_SENDQ " " SCTP_RWIND " " SCTP_RECVQ " "
6217     SCTP_STRS " " SCTP_STATE "\n"
6218     SCTP_LOCAL_" " SCTP_REMOTE_" "
6219     SCTP_SWIND_" " SCTP_SENDQ_" " SCTP_RWIND_" " SCTP_RECVQ_" "
6220     SCTP_STRS_" " SCTP_STATE_"\n";
6221 
6222 static const char sctp_hdr_pid[] =
6223     SCTP_LOCAL " " SCTP_REMOTE " "
6224     SCTP_SWIND " " SCTP_SENDQ " " SCTP_RWIND " " SCTP_RECVQ " "
6225     SCTP_STRS " "
6226     SCTP_USER " " SCTP_PID " " SCTP_COMMAND " " SCTP_STATE "\n"
6227     SCTP_LOCAL_" " SCTP_REMOTE_" "
6228     SCTP_SWIND_" " SCTP_SENDQ_" " SCTP_RWIND_" " SCTP_RECVQ_" "
6229     SCTP_STRS_" "
6230     SCTP_USER_" " SCTP_PID_" " SCTP_COMMAND_" " SCTP_STATE_"\n";
6231 
6232 static const char sctp_hdr_pid_verbose[] =
6233     SCTP_LOCAL " " SCTP_REMOTE " "
6234     SCTP_SWIND " " SCTP_SENDQ " " SCTP_RWIND " " SCTP_RECVQ " "
6235     SCTP_STRS_" "
6236     SCTP_USER " " SCTP_PID " " SCTP_STATE " " SCTP_COMMAND "\n"
6237     SCTP_LOCAL_" " SCTP_REMOTE_" "
6238     SCTP_SWIND_" " SCTP_SENDQ_" " SCTP_RWIND_" " SCTP_RECVQ_" "
6239     SCTP_STRS_" "
6240     SCTP_USER_" " SCTP_PID_" " SCTP_STATE_" " SCTP_COMMAND_"\n";
6241 
6242 static const char *
6243 nssctp_state(int state, const mib2_transportMLPEntry_t *attr)
6244 {
6245 	static char sctpsbuf[50];
6246 	const char *cp;
6247 
6248 	switch (state) {
6249 	case MIB2_SCTP_closed:
6250 		cp = "CLOSED";
6251 		break;
6252 	case MIB2_SCTP_cookieWait:
6253 		cp = "COOKIE_WAIT";
6254 		break;
6255 	case MIB2_SCTP_cookieEchoed:
6256 		cp = "COOKIE_ECHOED";
6257 		break;
6258 	case MIB2_SCTP_established:
6259 		cp = "ESTABLISHED";
6260 		break;
6261 	case MIB2_SCTP_shutdownPending:
6262 		cp = "SHUTDOWN_PENDING";
6263 		break;
6264 	case MIB2_SCTP_shutdownSent:
6265 		cp = "SHUTDOWN_SENT";
6266 		break;
6267 	case MIB2_SCTP_shutdownReceived:
6268 		cp = "SHUTDOWN_RECEIVED";
6269 		break;
6270 	case MIB2_SCTP_shutdownAckSent:
6271 		cp = "SHUTDOWN_ACK_SENT";
6272 		break;
6273 	case MIB2_SCTP_listen:
6274 		cp = "LISTEN";
6275 		break;
6276 	default:
6277 		(void) snprintf(sctpsbuf, sizeof (sctpsbuf),
6278 		    "UNKNOWN STATE(%d)", state);
6279 		cp = sctpsbuf;
6280 		break;
6281 	}
6282 
6283 	if (RSECflag && attr != NULL && attr->tme_flags != 0) {
6284 		if (cp != sctpsbuf) {
6285 			(void) strlcpy(sctpsbuf, cp, sizeof (sctpsbuf));
6286 			cp = sctpsbuf;
6287 		}
6288 		if (attr->tme_flags & MIB2_TMEF_PRIVATE)
6289 			(void) strlcat(sctpsbuf, " P", sizeof (sctpsbuf));
6290 		if (attr->tme_flags & MIB2_TMEF_SHARED)
6291 			(void) strlcat(sctpsbuf, " S", sizeof (sctpsbuf));
6292 	}
6293 
6294 	return (cp);
6295 }
6296 
6297 static const mib2_sctpConnRemoteEntry_t *
6298 sctp_getnext_rem(const mib_item_t **itemp,
6299     const mib2_sctpConnRemoteEntry_t *current, uint32_t associd)
6300 {
6301 	const mib_item_t *item = *itemp;
6302 	const mib2_sctpConnRemoteEntry_t	*sre;
6303 
6304 	for (; item != NULL; item = item->next_item, current = NULL) {
6305 		if (!(item->group == MIB2_SCTP &&
6306 		    item->mib_id == MIB2_SCTP_CONN_REMOTE)) {
6307 			continue;
6308 		}
6309 
6310 		if (current != NULL) {
6311 			sre = (const mib2_sctpConnRemoteEntry_t *)
6312 			    ((const char *)current + sctpRemoteEntrySize);
6313 		} else {
6314 			sre = item->valp;
6315 		}
6316 		for (; (char *)sre < (char *)item->valp + item->length;
6317 		    sre = (const mib2_sctpConnRemoteEntry_t *)
6318 		    ((const char *)sre + sctpRemoteEntrySize)) {
6319 			if (sre->sctpAssocId != associd) {
6320 				continue;
6321 			}
6322 			*itemp = item;
6323 			return (sre);
6324 		}
6325 	}
6326 	*itemp = NULL;
6327 	return (NULL);
6328 }
6329 
6330 static const mib2_sctpConnLocalEntry_t *
6331 sctp_getnext_local(const mib_item_t **itemp,
6332     const mib2_sctpConnLocalEntry_t *current, uint32_t associd)
6333 {
6334 	const mib_item_t *item = *itemp;
6335 	const mib2_sctpConnLocalEntry_t	*sle;
6336 
6337 	for (; item != NULL; item = item->next_item, current = NULL) {
6338 		if (!(item->group == MIB2_SCTP &&
6339 		    item->mib_id == MIB2_SCTP_CONN_LOCAL)) {
6340 			continue;
6341 		}
6342 
6343 		if (current != NULL) {
6344 			sle = (const mib2_sctpConnLocalEntry_t *)
6345 			    ((const char *)current + sctpLocalEntrySize);
6346 		} else {
6347 			sle = item->valp;
6348 		}
6349 		for (; (char *)sle < (char *)item->valp + item->length;
6350 		    sle = (const mib2_sctpConnLocalEntry_t *)
6351 		    ((const char *)sle + sctpLocalEntrySize)) {
6352 			if (sle->sctpAssocId != associd) {
6353 				continue;
6354 			}
6355 			*itemp = item;
6356 			return (sle);
6357 		}
6358 	}
6359 	*itemp = NULL;
6360 	return (NULL);
6361 }
6362 
6363 static void
6364 sctp_pr_addr(int type, char *name, int namelen, const in6_addr_t *addr,
6365     int port)
6366 {
6367 	ipaddr_t	v4addr;
6368 	in6_addr_t	v6addr;
6369 
6370 	/*
6371 	 * Address is either a v4 mapped or v6 addr. If
6372 	 * it's a v4 mapped, convert to v4 before
6373 	 * displaying.
6374 	 */
6375 	switch (type) {
6376 	case MIB2_SCTP_ADDR_V4:
6377 		/* v4 */
6378 		v6addr = *addr;
6379 
6380 		IN6_V4MAPPED_TO_IPADDR(&v6addr, v4addr);
6381 		if (port > 0) {
6382 			(void) pr_ap(v4addr, port, "sctp", name, namelen);
6383 		} else {
6384 			(void) pr_addr(v4addr, name, namelen);
6385 		}
6386 		break;
6387 
6388 	case MIB2_SCTP_ADDR_V6:
6389 		/* v6 */
6390 		if (port > 0) {
6391 			(void) pr_ap6(addr, port, "sctp", name, namelen);
6392 		} else {
6393 			(void) pr_addr6(addr, name, namelen);
6394 		}
6395 		break;
6396 
6397 	default:
6398 		(void) snprintf(name, namelen, "<unknown addr type>");
6399 		break;
6400 	}
6401 }
6402 
6403 static boolean_t
6404 sctp_conn_report_item(const mib_item_t *head, boolean_t print_sctp_hdr,
6405     const mib2_sctpConnEntry_t *sp, const mib2_transportMLPEntry_t *attr,
6406     const mib2_socketInfoEntry_t *sie)
6407 {
6408 	char		lname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
6409 	char		fname[MAXHOSTNAMELEN + MAXHOSTNAMELEN + 1];
6410 	const mib2_sctpConnRemoteEntry_t	*sre = NULL;
6411 	const mib2_sctpConnLocalEntry_t	*sle = NULL;
6412 	const mib_item_t *local = head;
6413 	const mib_item_t *remote = head;
6414 	uint32_t	id = sp->sctpAssocId;
6415 	boolean_t	printfirst = B_TRUE;
6416 	proc_fdinfo_t	*ph;
6417 
6418 	if (print_sctp_hdr == B_TRUE) {
6419 		(void) puts(sctp_hdr);
6420 		if (Uflag)
6421 			(void) puts(Vflag ? sctp_hdr_pid_verbose: sctp_hdr_pid);
6422 		else
6423 			(void) puts(sctp_hdr_normal);
6424 
6425 		print_sctp_hdr = B_FALSE;
6426 	}
6427 
6428 	sctp_pr_addr(sp->sctpAssocRemPrimAddrType, fname, sizeof (fname),
6429 	    &sp->sctpAssocRemPrimAddr, sp->sctpAssocRemPort);
6430 	sctp_pr_addr(sp->sctpAssocRemPrimAddrType, lname, sizeof (lname),
6431 	    &sp->sctpAssocLocPrimAddr, sp->sctpAssocLocalPort);
6432 
6433 	if (Xflag)
6434 		sie_report(sie);
6435 
6436 	if (Uflag) {
6437 		for (ph = process_hash_get(sie, SOCK_STREAM, AF_INET);
6438 		    ph != NULL; ph = ph->ph_next_proc) {
6439 			(void) printf(
6440 			    SCTP_LOCAL_F " " SCTP_REMOTE_F " "
6441 			    SCTP_SWIND_F " " SCTP_SENDQ_F " "
6442 			    SCTP_RWIND_F " " SCTP_RECVQ_F " "
6443 			    SCTP_STRS_FI "/" SCTP_STRS_FO " "
6444 			    SCTP_USER_F " " SCTP_PID_F " ",
6445 			    lname, fname,
6446 			    sp->sctpConnEntryInfo.ce_swnd,
6447 			    sp->sctpConnEntryInfo.ce_sendq,
6448 			    sp->sctpConnEntryInfo.ce_rwnd,
6449 			    sp->sctpConnEntryInfo.ce_recvq,
6450 			    sp->sctpAssocInStreams,
6451 			    sp->sctpAssocOutStreams,
6452 			    ph->ph_username, ph->ph_pidstr);
6453 			if (Vflag) {
6454 				(void) printf(SCTP_STATE_F " %s\n",
6455 				    nssctp_state(sp->sctpAssocState, attr),
6456 				    ph->ph_psargs);
6457 			} else {
6458 				(void) printf(SCTP_COMMAND_F " %s\n",
6459 				    ph->ph_fname,
6460 				    nssctp_state(sp->sctpAssocState, attr));
6461 			}
6462 		}
6463 	} else {
6464 		(void) printf(
6465 		    SCTP_LOCAL_F " " SCTP_REMOTE_F " "
6466 		    SCTP_SWIND_F " " SCTP_SENDQ_F " "
6467 		    SCTP_RWIND_F " " SCTP_RECVQ_F " "
6468 		    SCTP_STRS_FI "/" SCTP_STRS_FO " %s\n",
6469 		    lname, fname,
6470 		    sp->sctpConnEntryInfo.ce_swnd,
6471 		    sp->sctpConnEntryInfo.ce_sendq,
6472 		    sp->sctpConnEntryInfo.ce_rwnd,
6473 		    sp->sctpConnEntryInfo.ce_recvq,
6474 		    sp->sctpAssocInStreams, sp->sctpAssocOutStreams,
6475 		    nssctp_state(sp->sctpAssocState, attr));
6476 	}
6477 
6478 	print_transport_label(attr);
6479 
6480 	if (!Vflag)
6481 		return (print_sctp_hdr);
6482 
6483 	/* Print remote addresses/local addresses on following lines */
6484 	while ((sre = sctp_getnext_rem(&remote, sre, id)) != NULL) {
6485 		if (!IN6_ARE_ADDR_EQUAL(&sre->sctpAssocRemAddr,
6486 		    &sp->sctpAssocRemPrimAddr)) {
6487 			if (printfirst == B_TRUE) {
6488 				(void) fputs("\t<Remote: ", stdout);
6489 				printfirst = B_FALSE;
6490 			} else {
6491 				(void) fputs(", ", stdout);
6492 			}
6493 			sctp_pr_addr(sre->sctpAssocRemAddrType, fname,
6494 			    sizeof (fname), &sre->sctpAssocRemAddr, -1);
6495 			if (sre->sctpAssocRemAddrActive == MIB2_SCTP_ACTIVE) {
6496 				(void) fputs(fname, stdout);
6497 			} else {
6498 				(void) printf("(%s)", fname);
6499 			}
6500 		}
6501 	}
6502 	if (printfirst == B_FALSE) {
6503 		(void) puts(">");
6504 		printfirst = B_TRUE;
6505 	}
6506 	while ((sle = sctp_getnext_local(&local, sle, id)) != NULL) {
6507 		if (!IN6_ARE_ADDR_EQUAL(&sle->sctpAssocLocalAddr,
6508 		    &sp->sctpAssocLocPrimAddr)) {
6509 			if (printfirst == B_TRUE) {
6510 				(void) fputs("\t<Local: ", stdout);
6511 				printfirst = B_FALSE;
6512 			} else {
6513 				(void) fputs(", ", stdout);
6514 			}
6515 			sctp_pr_addr(sle->sctpAssocLocalAddrType, lname,
6516 			    sizeof (lname), &sle->sctpAssocLocalAddr, -1);
6517 			(void) fputs(lname, stdout);
6518 		}
6519 	}
6520 	if (printfirst == B_FALSE) {
6521 		(void) puts(">");
6522 	}
6523 
6524 	return (print_sctp_hdr);
6525 }
6526 
6527 static void
6528 sctp_report(const mib_item_t *item)
6529 {
6530 	const mib2_sctpConnEntry_t	*sp;
6531 	boolean_t			print_sctp_hdr_once = B_TRUE;
6532 	mib2_transportMLPEntry_t	**attrs, **a, *aptr;
6533 	mib2_socketInfoEntry_t		**info, **i, *iptr;
6534 
6535 	/*
6536 	 * Preparation pass: the kernel returns separate entries for SCTP
6537 	 * connection table entries and Multilevel Port attributes.  We loop
6538 	 * through the attributes first and set up an array for each address
6539 	 * family.
6540 	 */
6541 	attrs = RSECflag ?
6542 	    gather_attrs(item, MIB2_SCTP, MIB2_SCTP_CONN, sctpEntrySize) :
6543 	    NULL;
6544 	info = Uflag ?
6545 	    gather_info(item, MIB2_SCTP, MIB2_SCTP_CONN, sctpEntrySize) :
6546 	    NULL;
6547 
6548 	a = attrs;
6549 	i = info;
6550 	for (; item != NULL; item = item->next_item) {
6551 
6552 		if (!(item->group == MIB2_SCTP &&
6553 		    item->mib_id == MIB2_SCTP_CONN))
6554 			continue;
6555 
6556 		for (sp = item->valp;
6557 		    (char *)sp < (char *)item->valp + item->length;
6558 		    sp = (mib2_sctpConnEntry_t *)((char *)sp + sctpEntrySize)) {
6559 			if (!(Aflag ||
6560 			    sp->sctpAssocState >= MIB2_SCTP_established))
6561 				continue;
6562 			aptr = a == NULL ? NULL : *a++;
6563 			iptr = i == NULL ? NULL : *i++;
6564 			print_sctp_hdr_once = sctp_conn_report_item(
6565 			    item, print_sctp_hdr_once, sp, aptr, iptr);
6566 		}
6567 	}
6568 	free(attrs);
6569 	free(info);
6570 }
6571 
6572 static char *
6573 plural(int n)
6574 {
6575 	return (n != 1 ? "s" : "");
6576 }
6577 
6578 static char *
6579 pluraly(int n)
6580 {
6581 	return (n != 1 ? "ies" : "y");
6582 }
6583 
6584 static char *
6585 plurales(int n)
6586 {
6587 	return (n != 1 ? "es" : "");
6588 }
6589 
6590 static char *
6591 pktscale(int n)
6592 {
6593 	static char buf[6];
6594 	char t;
6595 
6596 	if (n < 1024) {
6597 		t = ' ';
6598 	} else if (n < 1024 * 1024) {
6599 		t = 'k';
6600 		n /= 1024;
6601 	} else if (n < 1024 * 1024 * 1024) {
6602 		t = 'm';
6603 		n /= 1024 * 1024;
6604 	} else {
6605 		t = 'g';
6606 		n /= 1024 * 1024 * 1024;
6607 	}
6608 
6609 	(void) snprintf(buf, sizeof (buf), "%4u%c", n, t);
6610 	return (buf);
6611 }
6612 
6613 /* --------------------- mrt_report (netstat -m) -------------------------- */
6614 
6615 static void
6616 mrt_report(mib_item_t *item)
6617 {
6618 	int		jtemp = 0;
6619 	struct vifctl	*vip;
6620 	vifi_t		vifi;
6621 	struct mfcctl	*mfccp;
6622 	int		numvifs = 0;
6623 	int		nmfc = 0;
6624 	char		abuf[MAXHOSTNAMELEN + 4]; /* Include CIDR /<num>. */
6625 
6626 	if (!(family_selected(AF_INET)))
6627 		return;
6628 
6629 	for (; item; item = item->next_item) {
6630 		if (Xflag) {
6631 			(void) printf("[%4d] Group = %d, mib_id = %d, "
6632 			    "length = %d, valp = 0x%p\n", jtemp++,
6633 			    item->group, item->mib_id, item->length,
6634 			    item->valp);
6635 		}
6636 		if (item->group != EXPER_DVMRP)
6637 			continue;
6638 
6639 		switch (item->mib_id) {
6640 
6641 		case EXPER_DVMRP_VIF:
6642 			if (Xflag)
6643 				(void) printf("%u records for ipVifTable:\n",
6644 				    item->length/sizeof (struct vifctl));
6645 			if (item->length/sizeof (struct vifctl) == 0) {
6646 				(void) puts("\nVirtual Interface Table is "
6647 				    "empty");
6648 				break;
6649 			}
6650 
6651 			(void) puts("\nVirtual Interface Table\n"
6652 			    " Vif Threshold Rate_Limit Local-Address"
6653 			    "   Remote-Address     Pkt_in   Pkt_out");
6654 
6655 			for (vip = (struct vifctl *)item->valp;
6656 			    (char *)vip < (char *)item->valp + item->length;
6657 			    vip = (struct vifctl *)((char *)vip +
6658 			    vifctlSize)) {
6659 				if (vip->vifc_lcl_addr.s_addr == 0)
6660 					continue;
6661 				/* numvifs = vip->vifc_vifi; */
6662 
6663 				numvifs++;
6664 				(void) printf("  %2u       %3u       "
6665 				    "%4u %-15.15s",
6666 				    vip->vifc_vifi,
6667 				    vip->vifc_threshold,
6668 				    vip->vifc_rate_limit,
6669 				    pr_addr(vip->vifc_lcl_addr.s_addr,
6670 				    abuf, sizeof (abuf)));
6671 				(void) printf(" %-15.15s  %8u  %8u\n",
6672 				    (vip->vifc_flags & VIFF_TUNNEL) ?
6673 				    pr_addr(vip->vifc_rmt_addr.s_addr,
6674 				    abuf, sizeof (abuf)) : "",
6675 				    vip->vifc_pkt_in,
6676 				    vip->vifc_pkt_out);
6677 			}
6678 
6679 			(void) printf("Numvifs: %d\n", numvifs);
6680 			break;
6681 
6682 		case EXPER_DVMRP_MRT:
6683 			if (Xflag)
6684 				(void) printf("%u records for ipMfcTable:\n",
6685 				    item->length/sizeof (struct vifctl));
6686 			if (item->length/sizeof (struct vifctl) == 0) {
6687 				(void) puts("\nMulticast Forwarding Cache is "
6688 				    "empty");
6689 				break;
6690 			}
6691 
6692 			(void) puts("\nMulticast Forwarding Cache\n"
6693 			    "  Origin-Subnet                 Mcastgroup      "
6694 			    "# Pkts  In-Vif  Out-vifs/Forw-ttl");
6695 
6696 			for (mfccp = (struct mfcctl *)item->valp;
6697 			    (char *)mfccp < (char *)item->valp + item->length;
6698 			    mfccp = (struct mfcctl *)((char *)mfccp +
6699 			    mfcctlSize)) {
6700 
6701 				nmfc++;
6702 				(void) printf("  %-30.15s",
6703 				    pr_addr(mfccp->mfcc_origin.s_addr,
6704 				    abuf, sizeof (abuf)));
6705 				(void) printf("%-15.15s  %6s  %3u    ",
6706 				    pr_net(mfccp->mfcc_mcastgrp.s_addr,
6707 				    mfccp->mfcc_mcastgrp.s_addr,
6708 				    abuf, sizeof (abuf)),
6709 				    pktscale((int)mfccp->mfcc_pkt_cnt),
6710 				    mfccp->mfcc_parent);
6711 
6712 				for (vifi = 0; vifi < MAXVIFS; ++vifi) {
6713 					if (mfccp->mfcc_ttls[vifi]) {
6714 						(void) printf("      %u (%u)",
6715 						    vifi,
6716 						    mfccp->mfcc_ttls[vifi]);
6717 					}
6718 
6719 				}
6720 				(void) putchar('\n');
6721 			}
6722 			(void) printf("\nTotal no. of entries in cache: %d\n",
6723 			    nmfc);
6724 			break;
6725 		}
6726 	}
6727 	(void) putchar('\n');
6728 	(void) fflush(stdout);
6729 }
6730 
6731 /*
6732  * Get the stats for the cache named 'name'.  If prefix != 0, then
6733  * interpret the name as a prefix, and sum up stats for all caches
6734  * named 'name*'.
6735  */
6736 static void
6737 kmem_cache_stats(char *title, char *name, int prefix, int64_t *total_bytes)
6738 {
6739 	int len;
6740 	int alloc;
6741 	int64_t total_alloc = 0;
6742 	int alloc_fail, total_alloc_fail = 0;
6743 	int buf_size = 0;
6744 	int buf_avail;
6745 	int buf_total;
6746 	int buf_max, total_buf_max = 0;
6747 	int buf_inuse, total_buf_inuse = 0;
6748 	kstat_t *ksp;
6749 	char buf[256];
6750 
6751 	len = prefix ? strlen(name) : 256;
6752 
6753 	for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
6754 
6755 		if (strcmp(ksp->ks_class, "kmem_cache") != 0)
6756 			continue;
6757 
6758 		/*
6759 		 * Hack alert: because of the way streams messages are
6760 		 * allocated, every constructed free dblk has an associated
6761 		 * mblk.  From the allocator's viewpoint those mblks are
6762 		 * allocated (because they haven't been freed), but from
6763 		 * our viewpoint they're actually free (because they're
6764 		 * not currently in use).  To account for this caching
6765 		 * effect we subtract the total constructed free dblks
6766 		 * from the total allocated mblks to derive mblks in use.
6767 		 */
6768 		if (strcmp(name, "streams_mblk") == 0 &&
6769 		    strncmp(ksp->ks_name, "streams_dblk", 12) == 0) {
6770 			(void) safe_kstat_read(kc, ksp, NULL);
6771 			total_buf_inuse -=
6772 			    kstat_named_value(ksp, "buf_constructed");
6773 			continue;
6774 		}
6775 
6776 		if (strncmp(ksp->ks_name, name, len) != 0)
6777 			continue;
6778 
6779 		(void) safe_kstat_read(kc, ksp, NULL);
6780 
6781 		alloc		= kstat_named_value(ksp, "alloc");
6782 		alloc_fail	= kstat_named_value(ksp, "alloc_fail");
6783 		buf_size	= kstat_named_value(ksp, "buf_size");
6784 		buf_avail	= kstat_named_value(ksp, "buf_avail");
6785 		buf_total	= kstat_named_value(ksp, "buf_total");
6786 		buf_max		= kstat_named_value(ksp, "buf_max");
6787 		buf_inuse	= buf_total - buf_avail;
6788 
6789 		if (Vflag && prefix) {
6790 			(void) snprintf(buf, sizeof (buf), "%s%s", title,
6791 			    ksp->ks_name + len);
6792 			(void) printf("    %-18s %6u %9u %11u %11u\n",
6793 			    buf, buf_inuse, buf_max, alloc, alloc_fail);
6794 		}
6795 
6796 		total_alloc		+= alloc;
6797 		total_alloc_fail	+= alloc_fail;
6798 		total_buf_max		+= buf_max;
6799 		total_buf_inuse		+= buf_inuse;
6800 		*total_bytes		+= (int64_t)buf_inuse * buf_size;
6801 	}
6802 
6803 	if (buf_size == 0) {
6804 		(void) printf("%-22s [couldn't find statistics for %s]\n",
6805 		    title, name);
6806 		return;
6807 	}
6808 
6809 	if (Vflag && prefix)
6810 		(void) snprintf(buf, sizeof (buf), "%s_total", title);
6811 	else
6812 		(void) snprintf(buf, sizeof (buf), "%s", title);
6813 
6814 	(void) printf("%-22s %6d %9d %11lld %11d\n", buf,
6815 	    total_buf_inuse, total_buf_max, total_alloc, total_alloc_fail);
6816 }
6817 
6818 static void
6819 m_report(void)
6820 {
6821 	int64_t total_bytes = 0;
6822 
6823 	(void) puts("streams allocation:");
6824 	(void) printf("%63s\n", "cumulative  allocation");
6825 	(void) printf("%63s\n",
6826 	    "current   maximum       total    failures");
6827 
6828 	kmem_cache_stats("streams",
6829 	    "stream_head_cache", 0, &total_bytes);
6830 	kmem_cache_stats("queues", "queue_cache", 0, &total_bytes);
6831 	kmem_cache_stats("mblk", "streams_mblk", 0, &total_bytes);
6832 	kmem_cache_stats("dblk", "streams_dblk", 1, &total_bytes);
6833 	kmem_cache_stats("linkblk", "linkinfo_cache", 0, &total_bytes);
6834 	kmem_cache_stats("syncq", "syncq_cache", 0, &total_bytes);
6835 	kmem_cache_stats("qband", "qband_cache", 0, &total_bytes);
6836 
6837 	(void) printf("\n%lld Kbytes allocated for streams data\n",
6838 	    total_bytes / 1024);
6839 
6840 	(void) putchar('\n');
6841 	(void) fflush(stdout);
6842 }
6843 
6844 /* --------------------------------- */
6845 
6846 /*
6847  * Print an IPv4 address. Remove the matching part of the domain name
6848  * from the returned name.
6849  */
6850 static char *
6851 pr_addr(uint_t addr, char *dst, uint_t dstlen)
6852 {
6853 	char			*cp;
6854 	struct hostent		*hp = NULL;
6855 	static char		domain[MAXHOSTNAMELEN + 1];
6856 	static boolean_t	first = B_TRUE;
6857 	int			error_num;
6858 
6859 	if (first) {
6860 		first = B_FALSE;
6861 		if (sysinfo(SI_HOSTNAME, domain, MAXHOSTNAMELEN) != -1 &&
6862 		    (cp = strchr(domain, '.'))) {
6863 			(void) strncpy(domain, cp + 1, sizeof (domain));
6864 		} else
6865 			domain[0] = 0;
6866 	}
6867 	cp = NULL;
6868 	if (!Nflag) {
6869 		ns_lookup_start();
6870 		hp = getipnodebyaddr((char *)&addr, sizeof (uint_t), AF_INET,
6871 		    &error_num);
6872 		ns_lookup_end();
6873 		if (hp) {
6874 			if ((cp = strchr(hp->h_name, '.')) != NULL &&
6875 			    strcasecmp(cp + 1, domain) == 0)
6876 				*cp = 0;
6877 			cp = hp->h_name;
6878 		}
6879 	}
6880 	if (cp != NULL) {
6881 		(void) strncpy(dst, cp, dstlen);
6882 		dst[dstlen - 1] = 0;
6883 	} else {
6884 		(void) inet_ntop(AF_INET, (char *)&addr, dst, dstlen);
6885 	}
6886 	if (hp != NULL)
6887 		freehostent(hp);
6888 	return (dst);
6889 }
6890 
6891 /*
6892  * Print a non-zero IPv4 address.  Print "    --" if the address is zero.
6893  */
6894 static char *
6895 pr_addrnz(ipaddr_t addr, char *dst, uint_t dstlen)
6896 {
6897 	if (addr == INADDR_ANY) {
6898 		(void) strlcpy(dst, "    --", dstlen);
6899 		return (dst);
6900 	}
6901 	return (pr_addr(addr, dst, dstlen));
6902 }
6903 
6904 /*
6905  * Print an IPv6 address. Remove the matching part of the domain name
6906  * from the returned name.
6907  */
6908 static char *
6909 pr_addr6(const struct in6_addr *addr, char *dst, uint_t dstlen)
6910 {
6911 	char			*cp;
6912 	struct hostent		*hp = NULL;
6913 	static char		domain[MAXHOSTNAMELEN + 1];
6914 	static boolean_t	first = B_TRUE;
6915 	int			error_num;
6916 
6917 	if (first) {
6918 		first = B_FALSE;
6919 		if (sysinfo(SI_HOSTNAME, domain, MAXHOSTNAMELEN) != -1 &&
6920 		    (cp = strchr(domain, '.'))) {
6921 			(void) strncpy(domain, cp + 1, sizeof (domain));
6922 		} else
6923 			domain[0] = 0;
6924 	}
6925 	cp = NULL;
6926 	if (!Nflag) {
6927 		ns_lookup_start();
6928 		hp = getipnodebyaddr((char *)addr,
6929 		    sizeof (struct in6_addr), AF_INET6, &error_num);
6930 		ns_lookup_end();
6931 		if (hp) {
6932 			if ((cp = strchr(hp->h_name, '.')) != NULL &&
6933 			    strcasecmp(cp + 1, domain) == 0)
6934 				*cp = 0;
6935 			cp = hp->h_name;
6936 		}
6937 	}
6938 	if (cp != NULL) {
6939 		(void) strncpy(dst, cp, dstlen);
6940 		dst[dstlen - 1] = 0;
6941 	} else {
6942 		(void) inet_ntop(AF_INET6, (void *)addr, dst, dstlen);
6943 	}
6944 	if (hp != NULL)
6945 		freehostent(hp);
6946 	return (dst);
6947 }
6948 
6949 /* For IPv4 masks */
6950 static char *
6951 pr_mask(uint_t addr, char *dst, uint_t dstlen)
6952 {
6953 	uint8_t	*ip_addr = (uint8_t *)&addr;
6954 
6955 	(void) snprintf(dst, dstlen, "%d.%d.%d.%d",
6956 	    ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3]);
6957 	return (dst);
6958 }
6959 
6960 /*
6961  * For ipv6 masks format is : dest/mask
6962  * Does not print /128 to save space in printout. H flag carries this notion.
6963  */
6964 static char *
6965 pr_prefix6(const struct in6_addr *addr, uint_t prefixlen, char *dst,
6966     uint_t dstlen)
6967 {
6968 	char *cp;
6969 
6970 	if (IN6_IS_ADDR_UNSPECIFIED(addr) && prefixlen == 0) {
6971 		(void) strncpy(dst, "default", dstlen);
6972 		dst[dstlen - 1] = 0;
6973 		return (dst);
6974 	}
6975 
6976 	(void) pr_addr6(addr, dst, dstlen);
6977 	if (prefixlen != IPV6_ABITS) {
6978 		/* How much room is left? */
6979 		cp = strchr(dst, '\0');
6980 		if (dst + dstlen > cp) {
6981 			dstlen -= (cp - dst);
6982 			(void) snprintf(cp, dstlen, "/%d", prefixlen);
6983 		}
6984 	}
6985 	return (dst);
6986 }
6987 
6988 /* Print IPv4 address and port */
6989 static char *
6990 pr_ap(uint_t addr, uint_t port, char *proto,
6991     char *dst, uint_t dstlen)
6992 {
6993 	char *cp;
6994 
6995 	if (addr == INADDR_ANY) {
6996 		(void) strncpy(dst, "      *", dstlen);
6997 		dst[dstlen - 1] = 0;
6998 	} else {
6999 		(void) pr_addr(addr, dst, dstlen);
7000 	}
7001 	/* How much room is left? */
7002 	cp = strchr(dst, '\0');
7003 	if (dst + dstlen > cp + 1) {
7004 		*cp++ = '.';
7005 		dstlen -= (cp - dst);
7006 		dstlen--;
7007 		(void) portname(port, proto, cp, dstlen);
7008 	}
7009 	return (dst);
7010 }
7011 
7012 /* Print IPv6 address and port */
7013 static char *
7014 pr_ap6(const in6_addr_t *addr, uint_t port, char *proto,
7015     char *dst, uint_t dstlen)
7016 {
7017 	char *cp;
7018 
7019 	if (IN6_IS_ADDR_UNSPECIFIED(addr)) {
7020 		(void) strncpy(dst, "      *", dstlen);
7021 		dst[dstlen - 1] = 0;
7022 	} else {
7023 		(void) pr_addr6(addr, dst, dstlen);
7024 	}
7025 	/* How much room is left? */
7026 	cp = strchr(dst, '\0');
7027 	if (dst + dstlen + 1 > cp) {
7028 		*cp++ = '.';
7029 		dstlen -= (cp - dst);
7030 		dstlen--;
7031 		(void) portname(port, proto, cp, dstlen);
7032 	}
7033 	return (dst);
7034 }
7035 
7036 /*
7037  * Returns -2 to indicate a discontiguous mask.  Otherwise returns between
7038  * 0 and 32.
7039  */
7040 static int
7041 v4_cidr_len(uint_t mask)
7042 {
7043 	int rc = 0;
7044 	int i;
7045 
7046 	for (i = 0; i < 32; i++) {
7047 		if (mask & 0x1)
7048 			rc++;
7049 		else if (rc > 0)
7050 			return (-2);	/* Discontiguous IPv4 netmask. */
7051 
7052 		mask >>= 1;
7053 	}
7054 
7055 	return (rc);
7056 }
7057 
7058 static void
7059 append_v4_cidr_len(char *dst, uint_t dstlen, int prefixlen)
7060 {
7061 	char *prefixptr;
7062 
7063 	/* 4 bytes leaves room for '/' 'N' 'N' '\0' */
7064 	if (strlen(dst) <= dstlen - 4) {
7065 		prefixptr = dst + strlen(dst);
7066 	} else {
7067 		/*
7068 		 * Cut off last 3 chars of very-long DNS name.  All callers
7069 		 * should give us enough room, but name services COULD give us
7070 		 * a way-too-big name (see above).
7071 		 */
7072 		prefixptr = dst + strlen(dst) - 3;
7073 	}
7074 	/* At this point "prefixptr" is guaranteed to point to 4 bytes. */
7075 
7076 	if (prefixlen >= 0) {
7077 		if (prefixlen > 32)	/* Shouldn't happen, but... */
7078 			prefixlen = 32;
7079 		(void) snprintf(prefixptr, 4, "/%d", prefixlen);
7080 	} else if (prefixlen == -2) {
7081 		/* "/NM" == Noncontiguous Mask. */
7082 		(void) strcat(prefixptr, "/NM");
7083 	}
7084 	/* Else print nothing extra. */
7085 }
7086 
7087 /*
7088  * Return the name of the network whose address is given. The address is
7089  * assumed to be that of a net or subnet, not a host.
7090  */
7091 static char *
7092 pr_net(uint_t addr, uint_t mask, char *dst, uint_t dstlen)
7093 {
7094 	char		*cp = NULL;
7095 	struct netent	*np = NULL;
7096 	struct hostent	*hp = NULL;
7097 	uint_t		net;
7098 	int		subnetshift;
7099 	int		error_num;
7100 	int		prefixlen = -1;	/* -1 == Don't print prefix! */
7101 					/* -2 == Noncontiguous mask... */
7102 
7103 	if (addr == INADDR_ANY && mask == INADDR_ANY) {
7104 		(void) strlcpy(dst, "default", dstlen);
7105 		return (dst);
7106 	}
7107 
7108 	if (CIDRflag)
7109 		prefixlen = v4_cidr_len(ntohl(mask));
7110 
7111 	if (!Nflag && addr) {
7112 		if (mask == 0) {
7113 			if (IN_CLASSA(addr)) {
7114 				mask = (uint_t)IN_CLASSA_NET;
7115 				subnetshift = 8;
7116 			} else if (IN_CLASSB(addr)) {
7117 				mask = (uint_t)IN_CLASSB_NET;
7118 				subnetshift = 8;
7119 			} else {
7120 				mask = (uint_t)IN_CLASSC_NET;
7121 				subnetshift = 4;
7122 			}
7123 			/*
7124 			 * If there are more bits than the standard mask
7125 			 * would suggest, subnets must be in use. Guess at
7126 			 * the subnet mask, assuming reasonable width subnet
7127 			 * fields.
7128 			 */
7129 			while (addr & ~mask)
7130 				/* compiler doesn't sign extend! */
7131 				mask = (mask | ((int)mask >> subnetshift));
7132 			if (CIDRflag)
7133 				prefixlen = v4_cidr_len(mask);
7134 		}
7135 		net = addr & mask;
7136 		while ((mask & 1) == 0)
7137 			mask >>= 1, net >>= 1;
7138 		ns_lookup_start();
7139 		np = getnetbyaddr(net, AF_INET);
7140 		ns_lookup_end();
7141 		if (np && np->n_net == net)
7142 			cp = np->n_name;
7143 		else {
7144 			/*
7145 			 * Look for subnets in hosts map.
7146 			 */
7147 			ns_lookup_start();
7148 			hp = getipnodebyaddr((char *)&addr, sizeof (uint_t),
7149 			    AF_INET, &error_num);
7150 			ns_lookup_end();
7151 			if (hp)
7152 				cp = hp->h_name;
7153 		}
7154 	}
7155 	if (cp != NULL) {
7156 		(void) strlcpy(dst, cp, dstlen);
7157 	} else {
7158 		(void) inet_ntop(AF_INET, (char *)&addr, dst, dstlen);
7159 	}
7160 
7161 	append_v4_cidr_len(dst, dstlen, prefixlen);
7162 
7163 	if (hp != NULL)
7164 		freehostent(hp);
7165 	return (dst);
7166 }
7167 
7168 /*
7169  * Return the name of the network whose address is given.
7170  * The address is assumed to be a host address.
7171  */
7172 static char *
7173 pr_netaddr(uint_t addr, uint_t mask, char *dst, uint_t dstlen)
7174 {
7175 	char		*cp = NULL;
7176 	struct netent	*np = NULL;
7177 	struct hostent	*hp = NULL;
7178 	uint_t		net;
7179 	uint_t		netshifted;
7180 	int		subnetshift;
7181 	struct in_addr in;
7182 	int		error_num;
7183 	uint_t		nbo_addr = addr;	/* network byte order */
7184 	int		prefixlen = -1;	/* -1 == Don't print prefix! */
7185 					/* -2 == Noncontiguous mask... */
7186 
7187 	addr = ntohl(addr);
7188 	mask = ntohl(mask);
7189 	if (addr == INADDR_ANY && mask == INADDR_ANY) {
7190 		(void) strlcpy(dst, "default", dstlen);
7191 		return (dst);
7192 	}
7193 
7194 	if (CIDRflag)
7195 		prefixlen = v4_cidr_len(mask);
7196 
7197 	/* Figure out network portion of address (with host portion = 0) */
7198 	if (addr) {
7199 		/* Try figuring out mask if unknown (all 0s). */
7200 		if (mask == 0) {
7201 			if (IN_CLASSA(addr)) {
7202 				mask = (uint_t)IN_CLASSA_NET;
7203 				subnetshift = 8;
7204 			} else if (IN_CLASSB(addr)) {
7205 				mask = (uint_t)IN_CLASSB_NET;
7206 				subnetshift = 8;
7207 			} else {
7208 				mask = (uint_t)IN_CLASSC_NET;
7209 				subnetshift = 4;
7210 			}
7211 			/*
7212 			 * If there are more bits than the standard mask
7213 			 * would suggest, subnets must be in use. Guess at
7214 			 * the subnet mask, assuming reasonable width subnet
7215 			 * fields.
7216 			 */
7217 			while (addr & ~mask)
7218 				/* compiler doesn't sign extend! */
7219 				mask = (mask | ((int)mask >> subnetshift));
7220 			if (CIDRflag)
7221 				prefixlen = v4_cidr_len(mask);
7222 		}
7223 		net = netshifted = addr & mask;
7224 		while ((mask & 1) == 0)
7225 			mask >>= 1, netshifted >>= 1;
7226 	}
7227 	else
7228 		net = netshifted = 0;
7229 
7230 	/* Try looking up name unless -n was specified. */
7231 	if (!Nflag) {
7232 		ns_lookup_start();
7233 		np = getnetbyaddr(netshifted, AF_INET);
7234 		ns_lookup_end();
7235 		if (np && np->n_net == netshifted)
7236 			cp = np->n_name;
7237 		else {
7238 			/*
7239 			 * Look for subnets in hosts map.
7240 			 */
7241 			ns_lookup_start();
7242 			hp = getipnodebyaddr((char *)&nbo_addr, sizeof (uint_t),
7243 			    AF_INET, &error_num);
7244 			ns_lookup_end();
7245 			if (hp)
7246 				cp = hp->h_name;
7247 		}
7248 
7249 		if (cp != NULL) {
7250 			(void) strlcpy(dst, cp, dstlen);
7251 			append_v4_cidr_len(dst, dstlen, prefixlen);
7252 			if (hp != NULL)
7253 				freehostent(hp);
7254 			return (dst);
7255 		}
7256 		/*
7257 		 * No name found for net: fallthru and return in decimal
7258 		 * dot notation.
7259 		 */
7260 	}
7261 
7262 	in.s_addr = htonl(net);
7263 	(void) inet_ntop(AF_INET, (char *)&in, dst, dstlen);
7264 	append_v4_cidr_len(dst, dstlen, prefixlen);
7265 	if (hp != NULL)
7266 		freehostent(hp);
7267 	return (dst);
7268 }
7269 
7270 /*
7271  * Return the filter mode as a string:
7272  *	1 => "INCLUDE"
7273  *	2 => "EXCLUDE"
7274  *	otherwise "<unknown>"
7275  */
7276 static char *
7277 fmodestr(uint_t fmode)
7278 {
7279 	switch (fmode) {
7280 	case 1:
7281 		return ("INCLUDE");
7282 	case 2:
7283 		return ("EXCLUDE");
7284 	default:
7285 		return ("<unknown>");
7286 	}
7287 }
7288 
7289 #define	MAX_STRING_SIZE	256
7290 
7291 static const char *
7292 pr_secattr(const sec_attr_list_t *attrs)
7293 {
7294 	int i;
7295 	char buf[MAX_STRING_SIZE + 1], *cp;
7296 	static char *sbuf;
7297 	static size_t sbuf_len;
7298 	struct rtsa_s rtsa;
7299 	const sec_attr_list_t *aptr;
7300 
7301 	if (!RSECflag || attrs == NULL)
7302 		return ("");
7303 
7304 	for (aptr = attrs, i = 1; aptr != NULL; aptr = aptr->sal_next)
7305 		i += MAX_STRING_SIZE;
7306 	if (i > sbuf_len) {
7307 		cp = realloc(sbuf, i);
7308 		if (cp == NULL) {
7309 			perror("realloc security attribute buffer");
7310 			return ("");
7311 		}
7312 		sbuf_len = i;
7313 		sbuf = cp;
7314 	}
7315 
7316 	cp = sbuf;
7317 	while (attrs != NULL) {
7318 		const mib2_ipAttributeEntry_t *iae = attrs->sal_attr;
7319 
7320 		/* note: effectively hard-coded in rtsa_keyword */
7321 		rtsa.rtsa_mask = RTSA_CIPSO | RTSA_SLRANGE | RTSA_DOI;
7322 		rtsa.rtsa_slrange = iae->iae_slrange;
7323 		rtsa.rtsa_doi = iae->iae_doi;
7324 
7325 		(void) snprintf(cp, MAX_STRING_SIZE,
7326 		    "<%s>%s ", rtsa_to_str(&rtsa, buf, sizeof (buf)),
7327 		    attrs->sal_next == NULL ? "" : ",");
7328 		cp += strlen(cp);
7329 		attrs = attrs->sal_next;
7330 	}
7331 	*cp = '\0';
7332 
7333 	return (sbuf);
7334 }
7335 
7336 /*
7337  * Pretty print a port number. If the Nflag was
7338  * specified, use numbers instead of names.
7339  */
7340 static char *
7341 portname(uint_t port, char *proto, char *dst, uint_t dstlen)
7342 {
7343 	struct servent *sp = NULL;
7344 
7345 	if (!Nflag && port) {
7346 		ns_lookup_start();
7347 		sp = getservbyport(htons(port), proto);
7348 		ns_lookup_end();
7349 	}
7350 	if (sp || port == 0)
7351 		(void) snprintf(dst, dstlen, "%.*s", MAXHOSTNAMELEN,
7352 		    sp ? sp->s_name : "*");
7353 	else
7354 		(void) snprintf(dst, dstlen, "%d", port);
7355 	dst[dstlen - 1] = 0;
7356 	return (dst);
7357 }
7358 
7359 void
7360 fail(int do_perror, char *message, ...)
7361 {
7362 	va_list args;
7363 
7364 	va_start(args, message);
7365 	(void) fputs("netstat: ", stderr);
7366 	(void) vfprintf(stderr, message, args);
7367 	va_end(args);
7368 	if (do_perror)
7369 		(void) fprintf(stderr, ": %s", strerror(errno));
7370 	(void) fputc('\n', stderr);
7371 	exit(2);
7372 }
7373 
7374 /*
7375  * fatal: print error message to stderr and
7376  * call exit(errcode)
7377  */
7378 static void
7379 fatal(int errcode, char *format, ...)
7380 {
7381 	if (format != NULL) {
7382 		va_list argp;
7383 
7384 		va_start(argp, format);
7385 		(void) vfprintf(stderr, format, argp);
7386 		va_end(argp);
7387 	}
7388 
7389 	exit(errcode);
7390 }
7391 
7392 
7393 /*
7394  * Return value of named statistic for given kstat_named kstat;
7395  * return 0LL if named statistic is not in list (use "ll" as a
7396  * type qualifier when printing 64-bit int's with printf() )
7397  */
7398 static uint64_t
7399 kstat_named_value(kstat_t *ksp, char *name)
7400 {
7401 	kstat_named_t *knp;
7402 	uint64_t value;
7403 
7404 	if (ksp == NULL)
7405 		return (0LL);
7406 
7407 	knp = kstat_data_lookup(ksp, name);
7408 	if (knp == NULL)
7409 		return (0LL);
7410 
7411 	switch (knp->data_type) {
7412 	case KSTAT_DATA_INT32:
7413 	case KSTAT_DATA_UINT32:
7414 		value = (uint64_t)(knp->value.ui32);
7415 		break;
7416 	case KSTAT_DATA_INT64:
7417 	case KSTAT_DATA_UINT64:
7418 		value = knp->value.ui64;
7419 		break;
7420 	default:
7421 		value = 0LL;
7422 		break;
7423 	}
7424 
7425 	return (value);
7426 }
7427 
7428 kid_t
7429 safe_kstat_read(kstat_ctl_t *kc, kstat_t *ksp, void *data)
7430 {
7431 	kid_t kstat_chain_id = kstat_read(kc, ksp, data);
7432 
7433 	if (kstat_chain_id == -1)
7434 		fail(1, "kstat_read(%p, '%s') failed", (void *)kc,
7435 		    ksp->ks_name);
7436 	return (kstat_chain_id);
7437 }
7438 
7439 /*
7440  * Parse a list of IRE flag characters into a bit field.
7441  */
7442 static uint_t
7443 flag_bits(const char *arg)
7444 {
7445 	const char *cp;
7446 	uint_t val;
7447 
7448 	if (*arg == '\0')
7449 		fatal(1, "missing flag list\n");
7450 
7451 	val = 0;
7452 	while (*arg != '\0') {
7453 		if ((cp = strchr(flag_list, *arg)) == NULL)
7454 			fatal(1, "%c: illegal flag\n", *arg);
7455 		val |= 1 << (cp - flag_list);
7456 		arg++;
7457 	}
7458 	return (val);
7459 }
7460 
7461 /*
7462  * Handle -f argument.  Validate input format, sort by keyword, and
7463  * save off digested results.
7464  */
7465 static void
7466 process_filter(char *arg)
7467 {
7468 	int idx;
7469 	int klen = 0;
7470 	char *cp, *cp2;
7471 	int val;
7472 	filter_t *newf;
7473 	struct hostent *hp;
7474 	int error_num;
7475 	uint8_t *ucp;
7476 	int maxv;
7477 
7478 	/* Look up the keyword first */
7479 	if (strchr(arg, ':') == NULL) {
7480 		idx = FK_AF;
7481 	} else {
7482 		for (idx = 0; idx < NFILTERKEYS; idx++) {
7483 			klen = strlen(filter_keys[idx]);
7484 			if (strncmp(filter_keys[idx], arg, klen) == 0 &&
7485 			    arg[klen] == ':')
7486 				break;
7487 		}
7488 		if (idx >= NFILTERKEYS)
7489 			fatal(1, "%s: unknown filter keyword\n", arg);
7490 
7491 		/* Advance past keyword and separator. */
7492 		arg += klen + 1;
7493 	}
7494 
7495 	if ((newf = malloc(sizeof (*newf))) == NULL) {
7496 		perror("filter");
7497 		exit(1);
7498 	}
7499 	switch (idx) {
7500 	case FK_AF:
7501 		if (strcmp(arg, "inet") == 0) {
7502 			newf->u.f_family = AF_INET;
7503 		} else if (strcmp(arg, "inet6") == 0) {
7504 			newf->u.f_family = AF_INET6;
7505 		} else if (strcmp(arg, "unix") == 0) {
7506 			newf->u.f_family = AF_UNIX;
7507 		} else {
7508 			newf->u.f_family = strtol(arg, &cp, 0);
7509 			if (arg == cp || *cp != '\0')
7510 				fatal(1, "%s: unknown address family.\n", arg);
7511 		}
7512 		break;
7513 
7514 	case FK_OUTIF:
7515 		if (strcmp(arg, "none") == 0) {
7516 			newf->u.f_ifname = NULL;
7517 			break;
7518 		}
7519 		if (strcmp(arg, "any") == 0) {
7520 			newf->u.f_ifname = "";
7521 			break;
7522 		}
7523 		val = strtol(arg, &cp, 0);
7524 		if (val <= 0 || arg == cp || cp[0] != '\0') {
7525 			if ((val = if_nametoindex(arg)) == 0) {
7526 				perror(arg);
7527 				exit(1);
7528 			}
7529 		}
7530 		newf->u.f_ifname = arg;
7531 		break;
7532 
7533 	case FK_DST:
7534 		V4MASK_TO_V6(IP_HOST_MASK, newf->u.a.f_mask);
7535 		if (strcmp(arg, "any") == 0) {
7536 			/* Special semantics; any address *but* zero */
7537 			newf->u.a.f_address = NULL;
7538 			(void) memset(&newf->u.a.f_mask, 0,
7539 			    sizeof (newf->u.a.f_mask));
7540 			break;
7541 		}
7542 		if (strcmp(arg, "none") == 0) {
7543 			newf->u.a.f_address = NULL;
7544 			break;
7545 		}
7546 		if ((cp = strrchr(arg, '/')) != NULL)
7547 			*cp++ = '\0';
7548 		hp = getipnodebyname(arg, AF_INET6, AI_V4MAPPED|AI_ALL,
7549 		    &error_num);
7550 		if (hp == NULL)
7551 			fatal(1, "%s: invalid or unknown host address\n", arg);
7552 		newf->u.a.f_address = hp;
7553 		if (cp == NULL) {
7554 			V4MASK_TO_V6(IP_HOST_MASK, newf->u.a.f_mask);
7555 		} else {
7556 			val = strtol(cp, &cp2, 0);
7557 			if (cp != cp2 && cp2[0] == '\0') {
7558 				/*
7559 				 * If decode as "/n" works, then translate
7560 				 * into a mask.
7561 				 */
7562 				if (hp->h_addr_list[0] != NULL &&
7563 				    IN6_IS_ADDR_V4MAPPED((in6_addr_t *)
7564 				    hp->h_addr_list[0])) {
7565 					maxv = IP_ABITS;
7566 				} else {
7567 					maxv = IPV6_ABITS;
7568 				}
7569 				if (val < 0 || val >= maxv)
7570 					fatal(1, "%d: not in range 0 to %d\n",
7571 					    val, maxv - 1);
7572 				if (maxv == IP_ABITS)
7573 					val += IPV6_ABITS - IP_ABITS;
7574 				ucp = newf->u.a.f_mask.s6_addr;
7575 				while (val >= 8)
7576 					*ucp++ = 0xff, val -= 8;
7577 				*ucp++ = (0xff << (8 - val)) & 0xff;
7578 				while (ucp < newf->u.a.f_mask.s6_addr +
7579 				    sizeof (newf->u.a.f_mask.s6_addr))
7580 					*ucp++ = 0;
7581 				/* Otherwise, try as numeric address */
7582 			} else if (inet_pton(AF_INET6,
7583 			    cp, &newf->u.a.f_mask) <= 0) {
7584 				fatal(1, "%s: illegal mask format\n", cp);
7585 			}
7586 		}
7587 		break;
7588 
7589 	case FK_FLAGS:
7590 		if (*arg == '+') {
7591 			newf->u.f.f_flagset = flag_bits(arg + 1);
7592 			newf->u.f.f_flagclear = 0;
7593 		} else if (*arg == '-') {
7594 			newf->u.f.f_flagset = 0;
7595 			newf->u.f.f_flagclear = flag_bits(arg + 1);
7596 		} else {
7597 			newf->u.f.f_flagset = flag_bits(arg);
7598 			newf->u.f.f_flagclear = ~newf->u.f.f_flagset;
7599 		}
7600 		break;
7601 
7602 	default:
7603 		assert(0);
7604 	}
7605 	newf->f_next = filters[idx];
7606 	filters[idx] = newf;
7607 }
7608 
7609 /* Determine if user wants this address family printed. */
7610 static boolean_t
7611 family_selected(int family)
7612 {
7613 	const filter_t *fp;
7614 
7615 	if (v4compat && family == AF_INET6)
7616 		return (B_FALSE);
7617 	if ((fp = filters[FK_AF]) == NULL)
7618 		return (B_TRUE);
7619 	while (fp != NULL) {
7620 		if (fp->u.f_family == family)
7621 			return (B_TRUE);
7622 		fp = fp->f_next;
7623 	}
7624 	return (B_FALSE);
7625 }
7626 
7627 /*
7628  * Convert the interface index to a string using the buffer `ifname', which
7629  * must be at least LIFNAMSIZ bytes.  We first try to map it to name.  If that
7630  * fails (e.g., because we're inside a zone and it does not have access to
7631  * interface for the index in question), just return "if#<num>".
7632  */
7633 static char *
7634 ifindex2str(uint_t ifindex, char *ifname)
7635 {
7636 	if (if_indextoname(ifindex, ifname) == NULL)
7637 		(void) snprintf(ifname, LIFNAMSIZ, "if#%d", ifindex);
7638 
7639 	return (ifname);
7640 }
7641 
7642 /*
7643  * print the usage line
7644  */
7645 static void
7646 usage(char *cmdname)
7647 {
7648 	(void) fprintf(stderr, "usage: %s [-anuv] [-f address_family] "
7649 	    "[-T d|u]\n", cmdname);
7650 	(void) fprintf(stderr, "       %s [-n] [-f address_family] "
7651 	    "[-P protocol] [-T d|u] [-g | -p | -s [interval [count]]]\n",
7652 	    cmdname);
7653 	(void) fprintf(stderr, "       %s -m [-v] [-T d|u] "
7654 	    "[interval [count]]\n", cmdname);
7655 	(void) fprintf(stderr, "       %s -i [-I interface] [-an] "
7656 	    "[-f address_family] [-T d|u] [interval [count]]\n", cmdname);
7657 	(void) fprintf(stderr, "       %s -r [-anv] "
7658 	    "[-f address_family|filter] [-T d|u]\n", cmdname);
7659 	(void) fprintf(stderr, "       %s -M [-ns] [-f address_family] "
7660 	    "[-T d|u]\n", cmdname);
7661 	(void) fprintf(stderr, "       %s -D [-I interface] "
7662 	    "[-f address_family] [-T d|u]\n", cmdname);
7663 	exit(EXIT_FAILURE);
7664 }
7665 
7666 /* -------------------UNIX Domain Sockets Report---------------------------- */
7667 
7668 #define	UDS_SO_PAIR	"(socketpair)"
7669 
7670 static char		*typetoname(t_scalar_t);
7671 static boolean_t	uds_report_item(struct sockinfo *, boolean_t);
7672 
7673 /*
7674  * Central definitions for the columns used in the reports.
7675  * For each column, there's a definition for the heading, the underline and
7676  * the formatted value.
7677  * Since most reports select different columns depending on command line
7678  * options, defining everything here avoids duplication in the report
7679  * format strings and makes it easy to make changes as necessary.
7680  */
7681 #define	UDS_ADDRESS		"Address         "
7682 #define	UDS_ADDRESS_		"----------------"
7683 #define	UDS_ADDRESS_F		"%-16.16s"
7684 #define	UDS_TYPE		"Type      "
7685 #define	UDS_TYPE_		"----------"
7686 #define	UDS_TYPE_F		"%-10.10s"
7687 #define	UDS_VNODE		"Vnode           "
7688 #define	UDS_VNODE_		"----------------"
7689 #define	UDS_VNODE_F		"%-16.16s"
7690 #define	UDS_CONN		"Conn            "
7691 #define	UDS_CONN_		"----------------"
7692 #define	UDS_CONN_F		"%-16.16s"
7693 #define	UDS_LOCAL		"Local Address                          "
7694 #define	UDS_LOCAL_		"---------------------------------------"
7695 #define	UDS_LOCAL_F		"%-39.39s"
7696 #define	UDS_REMOTE		"Remote Address                         "
7697 #define	UDS_REMOTE_		"---------------------------------------"
7698 #define	UDS_REMOTE_F		"%-39.39s"
7699 #define	UDS_USER		"User    "
7700 #define	UDS_USER_		"--------"
7701 #define	UDS_USER_F		"%-8.8s"
7702 #define	UDS_PID			"Pid   "
7703 #define	UDS_PID_		"------"
7704 #define	UDS_PID_F		"%6s"
7705 #define	UDS_COMMAND		"Command       "
7706 #define	UDS_COMMAND_		"--------------"
7707 #define	UDS_COMMAND_F		"%-14.14s"
7708 
7709 static const char uds_hdr[] = "\nActive UNIX domain sockets\n";
7710 
7711 static const char uds_hdr_normal[] =
7712     UDS_ADDRESS " " UDS_TYPE " " UDS_VNODE " " UDS_CONN " "
7713     UDS_LOCAL " " UDS_REMOTE "\n"
7714     UDS_ADDRESS_" " UDS_TYPE_" " UDS_VNODE_" " UDS_CONN_" "
7715     UDS_LOCAL_" " UDS_REMOTE_"\n";
7716 
7717 static const char uds_hdr_pid[] =
7718     UDS_ADDRESS " " UDS_TYPE " " UDS_USER " " UDS_PID " " UDS_COMMAND " "
7719     UDS_LOCAL " " UDS_REMOTE "\n"
7720     UDS_ADDRESS_ " " UDS_TYPE_" " UDS_USER_" " UDS_PID_" " UDS_COMMAND_" "
7721     UDS_LOCAL_" " UDS_REMOTE_"\n";
7722 
7723 static const char uds_hdr_pid_verbose[] =
7724     UDS_ADDRESS " " UDS_TYPE " " UDS_USER " " UDS_PID " "
7725     UDS_LOCAL " " UDS_REMOTE " " UDS_COMMAND "\n"
7726     UDS_ADDRESS_ " " UDS_TYPE_" " UDS_USER_" " UDS_PID_" "
7727     UDS_LOCAL_" " UDS_REMOTE_" " UDS_COMMAND_"\n";
7728 
7729 /*
7730  * Print a summary of connections related to unix protocols.
7731  */
7732 static void
7733 uds_report(kstat_ctl_t *kc)
7734 {
7735 	uint32_t	i;
7736 	kstat_t		*ksp;
7737 	struct sockinfo	*psi;
7738 	boolean_t	print_uds_hdr_once = B_TRUE;
7739 
7740 	if (kc == NULL) {
7741 		fail(0, "uds_report: No kstat");
7742 		exit(3);
7743 	}
7744 
7745 	if ((ksp = kstat_lookup(kc, "sockfs", 0, "sock_unix_list")) == NULL)
7746 		fail(0, "kstat_data_lookup failed\n");
7747 
7748 	if (kstat_read(kc, ksp, NULL) == -1)
7749 		fail(0, "kstat_read failed for sock_unix_list\n");
7750 
7751 	if (ksp->ks_ndata == 0)
7752 		return;			/* no AF_UNIX sockets found	*/
7753 
7754 	/*
7755 	 * Having ks_data set with ks_data == NULL shouldn't happen;
7756 	 * If it does, the sockfs kstat is seriously broken.
7757 	 */
7758 	if ((psi = ksp->ks_data) == NULL)
7759 		fail(0, "uds_report: no kstat data\n");
7760 
7761 	for (i = 0; i < ksp->ks_ndata; i++) {
7762 
7763 		print_uds_hdr_once = uds_report_item(psi, print_uds_hdr_once);
7764 
7765 		/* If si_size didn't get filled in, then we're done */
7766 		if (psi->si_size == 0 ||
7767 		    !IS_P2ALIGNED(psi->si_size, sizeof (psi)))
7768 			break;
7769 
7770 		/* Point to the next sockinfo in the array */
7771 		psi = (struct sockinfo *)(((char *)psi) + psi->si_size);
7772 	}
7773 }
7774 
7775 static boolean_t
7776 uds_report_item(struct sockinfo *psi, boolean_t first)
7777 {
7778 	char *laddr, *raddr;
7779 	proc_fdinfo_t *ph;
7780 
7781 	if (first) {
7782 		(void) printf("%s", uds_hdr);
7783 		if (Uflag)
7784 			(void) printf("%s",
7785 			    Vflag ? uds_hdr_pid_verbose : uds_hdr_pid);
7786 		else
7787 			(void) printf("%s", uds_hdr_normal);
7788 
7789 		first = B_FALSE;
7790 	}
7791 
7792 	raddr = laddr = "";
7793 
7794 	if ((psi->si_state & SS_ISBOUND) &&
7795 	    strlen(psi->si_laddr_sun_path) != 0 &&
7796 	    psi->si_laddr_soa_len != 0) {
7797 		if (psi->si_faddr_noxlate) {
7798 			laddr = UDS_SO_PAIR;
7799 		} else {
7800 			if (psi->si_laddr_soa_len >
7801 			    sizeof (psi->si_laddr_family))
7802 				laddr = psi->si_laddr_sun_path;
7803 		}
7804 	}
7805 
7806 	if ((psi->si_state & SS_ISCONNECTED) &&
7807 	    strlen(psi->si_faddr_sun_path) != 0 &&
7808 	    psi->si_faddr_soa_len != 0) {
7809 		if (psi->si_faddr_noxlate) {
7810 			raddr = UDS_SO_PAIR;
7811 		} else {
7812 			if (psi->si_faddr_soa_len >
7813 			    sizeof (psi->si_faddr_family))
7814 				raddr = psi->si_faddr_sun_path;
7815 		}
7816 	}
7817 
7818 	/* Traditional output */
7819 	if (!Uflag) {
7820 		(void) printf(
7821 		    UDS_ADDRESS_F " " UDS_TYPE_F " " UDS_VNODE_F " "
7822 		    UDS_CONN_F " " UDS_LOCAL_F " " UDS_REMOTE_F "\n",
7823 		    psi->si_son_straddr,
7824 		    typetoname(psi->si_serv_type),
7825 		    (psi->si_state & SS_ISBOUND) &&
7826 		    psi->si_ux_laddr_sou_magic == SOU_MAGIC_EXPLICIT ?
7827 		    psi->si_lvn_straddr : "0000000",
7828 		    (psi->si_state & SS_ISCONNECTED) &&
7829 		    psi->si_ux_faddr_sou_magic == SOU_MAGIC_EXPLICIT ?
7830 		    psi->si_fvn_straddr : "0000000",
7831 		    laddr, raddr);
7832 		return (first);
7833 	}
7834 
7835 	mib2_socketInfoEntry_t sie = {
7836 		.sie_inode = psi->si_inode,
7837 		.sie_flags = 0
7838 	};
7839 
7840 	if (Xflag)
7841 		sie_report(&sie);
7842 
7843 	for (ph = process_hash_get(&sie,
7844 	    psi->si_serv_type == T_CLTS ?  SOCK_DGRAM : SOCK_STREAM, AF_UNIX);
7845 	    ph != NULL; ph = ph->ph_next_proc) {
7846 		if (Vflag) {
7847 			(void) printf(
7848 			    UDS_ADDRESS_F " " UDS_TYPE_F " "
7849 			    UDS_USER_F " " UDS_PID_F " "
7850 			    UDS_LOCAL_F " " UDS_REMOTE_F " %s\n",
7851 			    psi->si_son_straddr,
7852 			    typetoname(psi->si_serv_type),
7853 			    ph->ph_username, ph->ph_pidstr,
7854 			    laddr, raddr, ph->ph_psargs);
7855 		} else {
7856 			(void) printf(
7857 			    UDS_ADDRESS_F " " UDS_TYPE_F " "
7858 			    UDS_USER_F " " UDS_PID_F " " UDS_COMMAND_F " "
7859 			    UDS_LOCAL_F " " UDS_REMOTE_F "\n",
7860 			    psi->si_son_straddr,
7861 			    typetoname(psi->si_serv_type),
7862 			    ph->ph_username, ph->ph_pidstr, ph->ph_fname,
7863 			    laddr, raddr);
7864 		}
7865 
7866 	}
7867 
7868 	return (first);
7869 }
7870 
7871 static char *
7872 typetoname(t_scalar_t type)
7873 {
7874 	switch (type) {
7875 	case T_CLTS:
7876 		return ("dgram");
7877 
7878 	case T_COTS:
7879 		return ("stream");
7880 
7881 	case T_COTS_ORD:
7882 		return ("stream-ord");
7883 
7884 	default:
7885 		return ("");
7886 	}
7887 }
7888