2014-01-29 44 views
0

嗨,我想解析一個IP/UDP數據包的頭細節實際上是爲了得到時間戳,端口地址等。我知道我可以使用庫來做到這一點。所以,谷歌搜索了很多後,我發現了一個代碼通過行包在下面的方法來解析IP/UDP數據包頭細節過濾

void dump_UDP_packet(const unsigned char *packet, struct timeval ts, 
        unsigned int capture_len) 
{ 
    struct ip *ip; 
    struct UDP_hdr *udp; 
    unsigned int IP_header_length; 

    /* For simplicity, we assume Ethernet encapsulation. */ 

    if (capture_len < sizeof(struct ether_header)) 
    { 
     /* We didn't even capture a full Ethernet header, so we 
     * can't analyze this any further. 
     */ 
     too_short(ts, "Ethernet header"); 
     return; 
    } 

    /* Skip over the Ethernet header. */ 
    packet += sizeof(struct ether_header); 
    capture_len -= sizeof(struct ether_header); 

    if (capture_len < sizeof(struct ip)) 
    { /* Didn't capture a full IP header */ 
     too_short(ts, "IP header"); 
     return; 
    } 

    ip = (struct ip*) packet; 
    IP_header_length = ip->ip_hl * 4; /* ip_hl is in 4-byte words */ 

    if (capture_len < IP_header_length) 
    { /* didn't capture the full IP header including options */ 
     too_short(ts, "IP header with options"); 
     return; 
    } 

    if (ip->ip_p != IPPROTO_UDP) 
    { 
     problem_pkt(ts, "non-UDP packet"); 
     return; 
    } 

    /* Skip over the IP header to get to the UDP header. */ 
    packet += IP_header_length; 
    capture_len -= IP_header_length; 

    if (capture_len < sizeof(struct UDP_hdr)) 
    { 
     too_short(ts, "UDP header"); 
     return; 
    } 

    udp = (struct UDP_hdr*) packet; 

    printf("%s UDP src_port=%d dst_port=%d length=%d\n", 
      timestamp_string(ts), 
      ntohs(udp->uh_sport), 
      ntohs(udp->uh_dport), 
      ntohs(udp->uh_ulen)); 
} 

的事情是,我真的不知道是什麼,我應該用它來調用這個函數,即參數,包? timeval中?等我recieving使用套接字API通過偵聽的端口和使用的recv我的包()函數

for (;;) 
    { 
     len = sizeof(cliaddr); 
     n = recvfrom(sockfd,mesg,1000,0,(struct sockaddr *)&cliaddr,&len); 
     //sendto(sockfd,mesg,n,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr)); 
     printf("-------------------------------------------------------\n"); 

     printf("%s\n from:%s port number:%d",mesg,inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port); 
     printf("-------------------------------------------------------\n"); 
    } 

現在,這裏我可以使用的MESG []通過上述功能將數據包的詳細信息或者是還有其他方式可以從特定端口接收數據包。我應該爲timeVal使用什麼值。任何幫助對我都有用。在此先感謝

回答

0

這裏最相關的是你如何打開你的套接字。你用SOCK_RAW標誌創建插座嗎?如果是,則recvfrom將接收到可以直接發送到您的功能的RAW數據包。我不知道有關Windows,但在Linux上建立一個原始套接字代碼如下::

sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP)); 

的timeval中的說法是不包直接相關。它應該是你有這個包的時候。您將在recvfrom之後致電gettimeofday

0

也許你應該考慮使用libpcap(Packet CAPture庫),膽量爲tcpdump