Writing Tux
Linux-Mobile-Guide

Appendix C. Serial Infrared Port Sniffers

Sniffer by Gerd Knorr

This program by courtesy of Gerd Knorr. You may use it to sniff the traffic which is going trough your IrDA port for details of the protocol (change the default ttyS1 in the source if necessary):

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>

#define BUFSIZE 1024

int
read_and_print(int fd, int sec, int usec)
{
    int         rc,l,i;
    char        buf[BUFSIZE+1];
    fd_set      set;
    struct timeval  tv;
    
    if (sec || usec) {
    FD_ZERO(&set);
    FD_SET(fd,&set);
    tv.tv_sec  = sec;

    tv.tv_usec = usec;
    if (0 == select(fd+1,&set,NULL,NULL,&tv))
        return -1;
    }
    
    switch (rc = read(fd,buf,BUFSIZE)) {
    case 0:
    printf("EOF");
    exit(0);
    break;
    case -1:
    perror("read");
    exit(1);
    default:
    for (l = 0; l < rc; l+= 16) {
        printf("%04x  ",l);
        for (i = l; i < l+16; i++) {
        if (i < rc)
            printf("%02x ",buf[i]);
        else
            printf("-- ");
        if ((i%4) == 3)
            printf(" ");
        }
        for (i = l; i < l+16; i++) {

        if (i < rc)
            printf("%c",isalnum(buf[i]) ? buf[i] : '.');
        }
        printf("\n");
    }
    break;
    }
    return rc;
}

void
setlines(int fd, int rts, int dtr)
{
    int lines = 0;

    if (rts) lines |= TIOCM_RTS;
    if (dtr) lines |= TIOCM_DTR;
    
    ioctl(fd,TIOCMSET,&lines);
}

int main(int argc, char *argv[])
{
    int         ser,i;
    struct termios      saved_attributes,tattr;
    struct winsize      win;
    char        buf[16];
    
    if (-1 == (ser = open("/dev/ttyS1",O_RDWR))) {

    perror("open /dev/ttyS1");
    exit(1);
    }
    
    /* Set the terminal mode */
    tcgetattr (ser, &tattr);
    cfmakeraw (&tattr);
    cfsetospeed (&tattr,B9600);
    cfsetispeed (&tattr,B9600);
    tcsetattr (ser, 0, &tattr);
    
    setlines(ser,0,0);
#if 0
    tcsendbreak(ser,0);
#endif

    /* main loop */
    fprintf(stderr,"setup done\n");
    while (-1 != read_and_print(ser,30,0)) {
    usleep(100000);
    }
    
    return 0;
}