一、将网卡设置在混杂模式
su
密码:bogon:/home/lonely/code/sniffer# ifconfig eth0 promiscbogon:/home/lonely/code/sniffer# ifconfigeth0 Link encap:Ethernet HWaddr 00:0c:29:14:31:2c inet addr:192.168.26.128 Bcast:192.168.26.255 Mask:255.255.255.0 inet6 addr: fe80::20c:29ff:fe14:312c/64 Scope:Link UP BROADCAST RUNNING PROMISC MULTICAST MTU:1500 Metric:1 RX packets:373 errors:0 dropped:0 overruns:0 frame:0 TX packets:293 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:40867 (39.9 KiB) TX bytes:41109 (40.1 KiB) Interrupt:19 Base address:0x2000lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:22 errors:0 dropped:0 overruns:0 frame:0 TX packets:22 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:1981 (1.9 KiB) TX bytes:1981 (1.9 KiB)cat headers.h
代码
struct ip{ unsigned int ip_length: 4 ; unsigned int ip_version: 4 ; unsigned char ip_tos; unsigned short ip_total_length; unsigned short ip_id; unsigned short ip_flags; unsigned char ip_ttl; unsigned char ip_protocol; unsigned short ip_cksum; unsigned int ip_source; unsigned int ip_dest;}; struct tcp{ unsigned short tcp_source_port; unsigned short tcp_dest_port; unsigned int tcp_seqno; unsigned int tcp_ackno; unsigned int tcp_resl: 4 ,tcp_hlen: 4 ,tcp_fin: 1 ,tcp_syn: 1 ,tcp_rst: 1 ,tcp_psh: 1 ,tcp_ack: 1 ,tcp_urg: 1 ,tcp_res2: 2 ; unsigned short tcp_winsize; unsigned short tcp_cksum; unsigned short tcp_urgent;};
cat simple_tcp_sniff.c
代码
/* * stdio.h printf和std_out之类的基本输入输出函数 * sys/socket.h SOCK_RAW和IPPROT_TCP的定义 * netinet/in.h 定义 sockaddr_in * arpa/inet.h 网络函数 */ #include < stdio.h > #include < sys / socket.h > #include < netinet / in .h > #include < arpa / inet.h > /* 定义ip和tcp字段的结构 */ #include " headers.h " int main(){ int sock,bytes_recieved,fromlen; char buffer[ 65535 ]; struct sockaddr_in from; struct ip * ip; struct tcp * tcp; sock = socket(AF_INET,SOCK_RAW,IPPROTO_TCP); while ( 1 ) { fromlen = sizeof from; bytes_recieved = recvfrom(sock,buffer, sizeof buffer, 0 ,( struct sockaddr * ) & from, & fromlen); printf( " \nBytes received ::: %5d\n " ,bytes_recieved); printf( " Source address ::: %s\n " ,inet_ntoa(from.sin_addr)); ip = ( struct ip * )buffer; printf( " IP header length ::: %d\n " ,ip -> ip_length); printf( " Protocol ::: %d\n " ,ip -> ip_protocol); tcp = ( struct tcp * )(buffer + ( 4 * ip -> ip_length)); printf( " Source port ::: %d\n " ,ntohs(tcp -> tcp_source_port)); printf( " Dest port ::: %d\n " ,ntohs(tcp -> tcp_dest_port)); }}