takumi funada
/
pktwatcher
Packet sniffer (http header inspecter) Make: Japanese Edition Vol.10
main.cpp
- Committer:
- funax
- Date:
- 2010-08-14
- Revision:
- 0:5d9cf80e1669
File content as of revision 0:5d9cf80e1669:
// mbed packet watcher by musashinodenpa // #include "mbed.h" #include "HTTPClient.h" void analyse(char *buf, int size); int search(char* hay, int size, char* needle); unsigned long getTime(); void alert (); void printtime(); DigitalOut led_link(LED1); DigitalOut led_detect(LED2); DigitalOut led_3(LED3); DigitalOut led_4(LED4); DigitalOut led_red(p20); PwmOut motor(p21); Serial usb(USBTX, USBRX); Serial com(p13, p14); // for printer int count = 0; #define LIMIT 5 int main() { Ethernet ether; char buffer[0x600]; int size = 0; usb.baud(38400); com.baud(9600); com.format(8, Serial::Odd, 2); // stopbit=2, parity=odd led_red = 1; set_time(getTime()); printtime(); com.printf(" initialized.\n"); while (1) { if ((size = ether.receive()) != 0) { led_link = 0; ether.read(buffer, size); analyse(buffer, size); } led_link = ether.link(); if (count == LIMIT) { alert(); count++; // keep counting } } } void analyse(char *buf, int size) { if (size < 42) return; // too small packet if (buf[23] != 0x06) return; // not TCP/IP if ((buf[36]*256 + buf[37]) != 80) return; // not http port int r = search(buf, size, "Host:"); // retrieving host name if (r > 0) { char hostname[32] = ""; strncpy(hostname, &buf[r+1], strcspn(&buf[r+1], "\r\n")); if (NULL != strstr(hostname, "komachi.yomiuri.co.jp")) { //usb.printf("%s ", hostname); r = search(buf, r, "GET"); if (r > 0) { char uri[256] = ""; strncpy(uri, &buf[r+1], strcspn(&buf[r+1], "\r\n")); if (NULL != strstr(uri, ".htm")) { led_detect = 1; printtime(); com.printf(" %d/%d\n", ++count, LIMIT); //com.printf("%s\n", uri); } } } } } int search(char* hay, int size, char* needle) { int i = 0, pos = 0; int len = strlen(needle); for (i = 0; i < size; i++) { if (hay[i] == needle[pos]) { if (++pos > len-1) return(i+1); } else { pos = 0; } } return(-1); } unsigned long getTime() { char t[64]; char r[] = "1234567890.123"; HTTPClient http; http.get("http://ntp-a1.nict.go.jp/cgi-bin/jst", t); strncpy(r, strpbrk(t,"12"), sizeof(r)-1); // hacking return(atol(r) + 3600 * 9); // UCT to JST ;-) } void printtime() { time_t t = time(NULL); char buf[32]; strftime(buf, 32, "%Y/%m/%d %H:%M:%S", localtime(&t)); com.printf("%s", buf); } void alert () { motor = 0.1f; // drive slow wait_ms(3000); motor = 0; }