summaryrefslogtreecommitdiff
authorTroy D. Hanson <tdh@tkhanson.net>2012-03-16 08:36:55 (GMT)
committer Troy D. Hanson <tdh@tkhanson.net>2012-03-16 08:36:55 (GMT)
commit398714389b061e45eef18e1cf9c9afedfc7a33fb (patch)
tree55fd22536ec95bc4a76c9b8698a6f1c0f74d84b3
parent7ec15ab81c6486a54aebcf7a172bbe89603e3f24 (diff)
downloadmisc-master.zip
misc-master.tar.gz
misc-master.tar.bz2
histo testmaster
-rw-r--r--index.txt1
-rw-r--r--ncurses/Makefile6
-rw-r--r--ncurses/histo-test2.c52
3 files changed, 58 insertions, 1 deletions
diff --git a/index.txt b/index.txt
index 5f20362..cba6be0 100644
--- a/index.txt
+++ b/index.txt
@@ -55,6 +55,7 @@ Examples of using common libraries and other reusable bits:
| {t}pexit[pexit] | a C program that gets signalled when its parent exits using prctl | C
| {t}utf8[utf8] | macros for utf8 handling including character length, validity and utf32 conversion | C
| {t}looper[looper] | example of iterating over lines of input from file or stdin using readline | C
+| {t}ncurses[ncurses] | sliding bar charts and histograms using ncurses | C
|=================================================================================================================
:f: http://tkhanson.net/cgit.cgi/misc.git/plain/fifor/index.html
diff --git a/ncurses/Makefile b/ncurses/Makefile
index b9f496f..6db4a8c 100644
--- a/ncurses/Makefile
+++ b/ncurses/Makefile
@@ -1,5 +1,5 @@
SRCS=$(wildcard *.c)
-EXES=histogram histo-test slidogram hello
+EXES=histogram histo-test histo-test2 slidogram hello
CFLAGS=-g
LDFLAGS=-lncurses
@@ -9,6 +9,10 @@ histogram: histogram.o tpl.o
histo-test: histo-test.o tpl.o
+histo-test2: histo-test2.o tpl.o
+ $(CC) -o $@ $^ -lpcap
+
+
.PHONY: clean
clean:
rm -f $(EXES) *.o
diff --git a/ncurses/histo-test2.c b/ncurses/histo-test2.c
new file mode 100644
index 0000000..7b6dbd8
--- a/dev/null
+++ b/ncurses/histo-test2.c
@@ -0,0 +1,52 @@
+#include <stdio.h>
+#include <pcap.h>
+#include <assert.h>
+#include "tpl.h"
+
+char err[PCAP_ERRBUF_SIZE];
+const int maxsz = 1024;
+#define NBUCKETS 16
+int buckets[NBUCKETS], npackets;
+
+void report() {
+ int i,d;
+ tpl_node *tn = tpl_map("A(u)",&d);
+ for(i=0; i < NBUCKETS; i++) {
+ d = buckets[i];
+ tpl_pack(tn,1);
+ buckets[i]=0; /* reset */
+ }
+ tpl_dump(tn,TPL_FD,1); /* write to stdout */
+ tpl_free(tn);
+}
+
+void cb(u_char *data, const struct pcap_pkthdr *hdr, const u_char *pkt) {
+ //printf("packet of length %d\n", hdr->len);
+ int bucket = (1.0 * hdr->caplen / maxsz) * NBUCKETS; assert(bucket < NBUCKETS);
+ buckets[bucket]++;
+ if (npackets++ >= 100) {report(); npackets=0;}
+}
+
+int main(int argc, char *argv[]) {
+ pcap_t *p=NULL;
+ int rc=-1;
+ char *dev;
+
+ dev = (argc > 1) ? argv[1] : pcap_lookupdev(err);
+ if (dev == NULL) {
+ fprintf(stderr, "no device: %s\n", err);
+ goto done;
+ }
+
+ p = pcap_open_live(dev, maxsz, 1, 0, err);
+ if (p == NULL) {
+ fprintf(stderr, "can't open %s: %s\n", dev, err);
+ goto done;
+ }
+
+ rc = pcap_loop(p, 0, cb, NULL);
+
+ done:
+ return rc;
+}
+