Tcprstat is used by Percona to monitor MySQL response time. However, any response time running on the TCP protocol can be used.
Tcprstat, like Tcpdump, uses the Libpcap library to grab packets and then analyzes the crawled TCP packets through the program.
1, through the analysis of the source IP and destination IP, see that IP is the local IP, to determine whether the package (Request packet) or out of the package (response package).
2, if the packet data size is 0, then skip, no longer processing. A data size of 0 is considered a TCP control package.
3. If the packet is an incoming packet (Request packet), insert a record into the hash table.
4. If the packet is an out-of-package (response packet), the time difference is calculated using the current package and the response packet in the previously inserted hash table. and delete the previous package in the hash table.
The code for the packet analysis is in the process-packet.c file, in the following way:
int Process_ip (pcap_t *dev, const struct IP *ip, struct Timeval TV) {char src[16], dst[16], *addr; int incoming; unsigned len; Addr = Inet_ntoa (IP->IP_SRC); strncpy (src, addr, 15); SRC[15] = ' + '; Addr = Inet_ntoa (IP->IP_DST); strncpy (DST, addr, 15); DST[15] = ' + '; if (is_local_address (IP->IP_SRC)) incoming = 0; else if (is_local_address (IP->IP_DST)) incoming = 1; else return 1; Len = htons (Ip->ip_len); Switch (ip->ip_p) {struct TCPHDR *tcp; uint16_t Sport, Dport, Lport, Rport; unsigned datalen; Case ipproto_tcp:tcp = (struct TCPHDR *) ((unsigned char *) IP + sizeof (struct IP)); #if defined (__FAVOR_BSD) sport = Ntohs (tcp->th_sport); Dport = Ntohs (Tcp->th_dport); Datalen = len-sizeof (struct IP)-Tcp->th_off * 4; 4 bits offset #else sport = Ntohs (Tcp->source); Dport = Ntohs (tcp->dest); Datalen = len-sizeof (struct IP)-Tcp->doff * 4; #endif//Capture only "data" packets, ignore TCP cont Rol if (Datalen = = 0) break; if (incoming) {lport = Dport; Rport = sport; Inbound (TV, IP->IP_DST, Ip->ip_src, Lport, Rport); } else {lport = sport; Rport = Dport; Outbound (TV, IP->IP_SRC, IP->IP_DST, Lport, Rport); } break; Default:break; } return 0; }
PS: In this file, the Process_packet method user obtains the header information.
Analysis of TCP packet in Tcprstat source code analysis