2014-01-29 46 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