如题。纯粹是调试程序的需要。

解决方案 »

  1.   


    下面的源代码取至Chad Renfro的>
    一文中
    /************************Tcp_sniff_2.c********************/
    1.#include  
    2.#include  
    3.#include
    4.#include
    5.#include
    6.#include
    7.#include  
    8.#include
    9.#include "headers.h"#define INTERFACE "eth0" /*Prototype area*/10.int Open_Raw_Socket(void); 
    11.int Set_Promisc(char *interface, int sock);                                 ?
    12.int main() {  
    13.int sock, bytes_recieved, fromlen;  
    14.char buffer[65535];
    15.struct sockaddr_in from; 
    16.struct ip *ip;
    17.struct tcp *tcp;  
    18.sock = Open_Raw_Socket();
    19. Set_Promisc(INTERFACE, sock);20. while(1)
    22. {
    23. fromlen = sizeof from;
    24. bytes_recieved = recvfrom(sock, buffer, sizeof buffer, 0, (struct sockaddr
    *)&from, &fromlen);
    25. printf("\nBytes received ::: %5d\n",bytes_recieved);
    26. printf("Source address ::: %s\n",inet_ntoa(from.sin_addr));
    27. ip = (struct ip *)buffer;
    /*See if this is a TCP packet*/
    28. if(ip->ip_protocol == 6) {
    29. printf("IP header length ::: %d\n",ip->ip_length);
    30. printf("Protocol ::: %d\n",ip->ip_protocol);
    31. tcp = (struct tcp *)(buffer + (4*ip->ip_length));                           ?
    32. printf("Source port ::: %d\n",ntohs(tcp->tcp_source_port));
    33. printf("Dest port ::: %d\n",ntohs(tcp->tcp_dest_port));
    34. }35. }
    36.}
    37.int Open_Raw_Socket() {    
    38. int sock;
    39. if((sock = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) ip_protocol == 6) ,如果
    答案是,tcp信息包从整个IP/TCP包 buffer + (4*ip->ip_length)
    地址处开始,所以31行 tcp = (struct tcp *)(buffer + (4*ip->ip_length)),然后对应
    结构把你所需要的信息输出。
    /*************************headers.h**************************/
    /*structure of an ip header*/ 
    struct ip {   
    unsigned int ip_length:4; /*little-endian*/ 
    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;  
    };/* Structure of a TCP header */
    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, /*little-endian*/
    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;
    };