全部博文(146)
分类: LINUX
2008-01-02 17:08:53
一个简单的数据包截获程序
/* a test sniff program
*/
#include
#include
#include
#include
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_res1: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;
};
int main()
{
int sock,bytes_received,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_received=recvfrom(sock,buffer,sizeof(buffer),0,(struct sockaddr*)&from
,&fromlen);
printf("\nBytes received:::%5d\n",bytes_received);
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));
}
}