How to show accepted TCP connections on FreeBSD using Dtrace


June 2013.
As of 2013-06-19, the DTrace TCP provider is not available in FreeBSD, so we need a workaround.


#!/usr/sbin/dtrace -s

fbt::tcp_usr_accept:entry
{
this->inp = (struct inpcb*)(args[0]->so_pcb);
this->inp_lport = this->inp->inp_inc.inc_ie.ie_lport;
this->inp_fport = this->inp->inp_inc.inc_ie.ie_fport;
printf("%d.%d.%d.%d:%d -> ",
((unsigned char *)&this->inp->inp_inc.inc_ie.ie_dependfaddr.ie46_foreign.ia46_addr4.s_addr)[0],
((unsigned char *)&this->inp->inp_inc.inc_ie.ie_dependfaddr.ie46_foreign.ia46_addr4.s_addr)[1],
((unsigned char *)&this->inp->inp_inc.inc_ie.ie_dependfaddr.ie46_foreign.ia46_addr4.s_addr)[2],
((unsigned char *)&this->inp->inp_inc.inc_ie.ie_dependfaddr.ie46_foreign.ia46_addr4.s_addr)[3],
ntohs(this->inp_fport)
);

printf("%d.%d.%d.%d:%d\n",
((unsigned char *)&this->inp->inp_inc.inc_ie.ie_dependladdr.ie46_local.ia46_addr4.s_addr)[0],
((unsigned char *)&this->inp->inp_inc.inc_ie.ie_dependladdr.ie46_local.ia46_addr4.s_addr)[1],
((unsigned char *)&this->inp->inp_inc.inc_ie.ie_dependladdr.ie46_local.ia46_addr4.s_addr)[2],
((unsigned char *)&this->inp->inp_inc.inc_ie.ie_dependladdr.ie46_local.ia46_addr4.s_addr)[3],
ntohs(this->inp_lport)
);
}

Sample output:

2 20578 tcp_usr_accept:entry 10.0.0.13:34529 -> 10.0.0.10:80
2 20578 tcp_usr_accept:entry 10.0.0.13:34533 -> 10.0.0.10:80
2 20578 tcp_usr_accept:entry 10.0.0.10:34553 -> 10.0.0.12:3306
2 20578 tcp_usr_accept:entry 10.0.0.13:34555 -> 10.0.0.10:80
2 20578 tcp_usr_accept:entry 10.0.0.10:34557 -> 10.0.0.12:3306
3 20578 tcp_usr_accept:entry 10.0.0.13:34461 -> 10.0.0.10:80
3 20578 tcp_usr_accept:entry 10.0.0.10:34474 -> 10.0.0.12:3306
3 20578 tcp_usr_accept:entry 10.0.0.13:34504 -> 10.0.0.10:80
3 20578 tcp_usr_accept:entry 10.0.0.13:34514 -> 10.0.0.10:80
3 20578 tcp_usr_accept:entry 10.0.0.13:34518 -> 10.0.0.10:80


System:

FreeBSD hostmaster1.example.com 9.1-STABLE FreeBSD 9.1-STABLE #0 r248486: Thu Jun 13 00:23:59 CEST 2013 root@hostmaster1.example.com:/usr/obj/usr/src/sys/HOSTMASTER1 amd64