最基本的,在linux i386上 代码:
//netdump.c
#include #include #include
#include #include
#include #include
#include #include #include
#include #include
#include #include #include
void die(char *why, int n) { perror(why); exit(n); }
int do_promisc(char *nif, int sock ) { struct ifreq ifr;
strncpy(ifr.ifr_name, nif,strlen(nif)+1); if((ioctl(sock,
SIOCGIFFLAGS, &ifr) == -1)) { die("ioctl", 2); }
ifr.ifr_flags |= IFF_PROMISC; if(ioctl(sock, SIOCSIFFLAGS, &ifr) == -1
) { die("ioctl", 3); } }
char buf[2*32767];
main() { struct sockaddr_in addr; struct iphdr *ip; struct
tcphdr *tcp; int sock, r, len; char *data; char ss[32], dd[32];
if((sock = socket(AF_INET,SOCK_RAW,IPPROTO_TCP)) == -1) die("socket", 1);
do_promisc("eth0", sock); for(;;) { len =
sizeof(addr); r = recvfrom(sock,(char *)buf,sizeof(buf),0,(struct
sockaddr *)&addr,&len); buf[r] = 0; ip = (struct iphdr
*)buf; tcp = (struct tcphdr *)(buf + sizeof(struct iphdr));
printf("PktSize: %d IPLEN %d PROT %d %s:%d-->%s:%d %d \n", r,
ip->tot_len, ip->protocol, strcpy(ss, inet_ntoa(*(struct
in_addr*)&(ip->saddr))), ntohs(tcp->source), strcpy(dd,
inet_ntoa(*(struct in_addr*)&(ip->daddr))), ntohs(tcp->dest),
tcp->doff ); data = (char*)tcp + 4*tcp->doff;
printf("data = %s\n", data); }
} |