xref: /illumos-gate/usr/src/cmd/dtrace/demo/tcp/tcpsnoop.d (revision 8d0c3d29bb99f6521f2dc5058a7e4debebad7899)
1 #!/usr/sbin/dtrace -s
2 /*
3  * tcpsnoop - snoop TCP network packets by process.
4  *	Written using DTrace tcp Provider.
5  *
6  * This analyses TCP network packets and prints the responsible PID plus
7  * standard details such as IP address and port. This captures traffic
8  * from existing and newly created TCP connections. It can help identify
9  * which processes are causing TCP traffic.
10  *
11  * SEE ALSO: snoop -rS
12  *
13  * CDDL HEADER START
14  *
15  * The contents of this file are subject to the terms of the
16  * Common Development and Distribution License (the "License").
17  * You may not use this file except in compliance with the License.
18  *
19  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
20  * or http://www.opensolaris.org/os/licensing.
21  * See the License for the specific language governing permissions
22  * and limitations under the License.
23  *
24  * When distributing Covered Code, include this CDDL HEADER in each
25  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
26  * If applicable, add the following below this CDDL HEADER, with the
27  * fields enclosed by brackets "[]" replaced with your own identifying
28  * information: Portions Copyright [yyyy] [name of copyright owner]
29  *
30  * CDDL HEADER END
31  */
32 /*
33  * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
34  *
35  * Portions Copyright 2010 Brendan Gregg
36  */
37 
38 #pragma D option quiet
39 #pragma D option switchrate=10hz
40 
41 dtrace:::BEGIN
42 {
43 	printf("%6s %6s %15s:%-5s      %15s:%-5s %6s %s\n",
44 	    "TIME", "PID", "LADDR", "PORT", "RADDR", "PORT", "BYTES", "FLAGS");
45 }
46 
47 tcp:::send
48 {
49 	this->length = args[2]->ip_plength - args[4]->tcp_offset;
50 	printf("%6d %6d %15s:%-5d  ->  %15s:%-5d %6d (",
51 	    timestamp/1000, args[1]->cs_pid, args[2]->ip_saddr,
52 	    args[4]->tcp_sport, args[2]->ip_daddr, args[4]->tcp_dport,
53 	    this->length);
54 }
55 
56 tcp:::receive
57 {
58 	this->length = args[2]->ip_plength - args[4]->tcp_offset;
59 	printf("%6d %6d %15s:%-5d  <-  %15s:%-5d %6d (",
60 	    timestamp/1000, args[1]->cs_pid, args[2]->ip_daddr,
61 	    args[4]->tcp_dport, args[2]->ip_saddr, args[4]->tcp_sport,
62 	    this->length);
63 }
64 
65 tcp:::send,
66 tcp:::receive
67 {
68 	printf("%s", args[4]->tcp_flags & TH_FIN ? "FIN|" : "");
69 	printf("%s", args[4]->tcp_flags & TH_SYN ? "SYN|" : "");
70 	printf("%s", args[4]->tcp_flags & TH_RST ? "RST|" : "");
71 	printf("%s", args[4]->tcp_flags & TH_PUSH ? "PUSH|" : "");
72 	printf("%s", args[4]->tcp_flags & TH_ACK ? "ACK|" : "");
73 	printf("%s", args[4]->tcp_flags & TH_URG ? "URG|" : "");
74 	printf("%s", args[4]->tcp_flags & TH_ECE ? "ECE|" : "");
75 	printf("%s", args[4]->tcp_flags & TH_CWR ? "CWR|" : "");
76 	printf("%s", args[4]->tcp_flags == 0 ? "null " : "");
77 	printf("\b)\n");
78 }
79