By kcpoon on 3月 31, 2011
Sometimes we got questions from customers about how to retrieve basic network statistics (such as data like `netstat -sP tcp`) programmatically. The correct way is to use SNMP! But sometimes they just want to get a simple counter, say the number of current established TCP connection (tcpCurrEstab). "Is there a quick and dirty way?" they asked. Yes, there is but use it at your own risk
The global network MIB2 statistics are currently kept using kstat(3KSTAT). For example, `kstat -m udp -c mib2` gives out the following UDP MIB2 counters.
module: udp instance: 0
name: udp class: mib2
So one can write a small program using kstat(3KSTAT) calls to get standard network MIB2 counters. As an example, the following are the simple steps to get SCTP counters.
1. Use kstat_open(3KSTAT) to get a handle.
2. Use kstat_lookup(3KSTAT) (module is "sctp", instance is 0, name is "sctp") to get the SCTP kstat_t *.
3. Use kstat_read(3KSTAT) to read in the SCTP kstat_t *.
4a. Use kstat_data_lookup(3KSTAT) to get to individual field, say "sctpInClosed". SCTP kstat_t uses KSTAT_TYPE_NAMED type. So the returned value of kstat_data_lookup() is kstat_named_t *. Use data_type in kstat_named_t to find out if the value is a 32 bit or 64 bit integer.
4b. Or use the SCTP kstat_t to get all the fields. The ks_data field in kstat_t is an array of kstat_named_t in this case.
5. Call kstat_close(3KSTAT) to close the handle.
Check all the related man pages for further details on the usage.