11.4.7 定位应用层报文数据的编程方法
定位了UDP和TCP头部地址后,其中的数据部分为应用层报文数据。根据TCP和UDP的协议获得应用程序指针的代码如下:
char*app_data = NULL; /*应用数据指针*/
int app_len = 0; /*应用数据长度*/
/*获得TCP或者UDP的应用数据*/
if(p_iphdr->protocol==6)
{
struct tcphdr*p_tcphdr = (struct tcphdr*)(p_iphdr+p_iphdr->ihl*4);
/*取得TCP报头*/
app_data = p_tcphdr + 20; /*获得TCP协议部分的应用数据地址*/
app_len = n - 16 - p_iphdr->ihl*4 - 20;/*获得TCP协议部分的应用数据长度*/
}else if(p_iphdr->protocol==17)
{
struct udphdr*p_udphdr = (struct udphdr*)(p_iphdr+p_iphdr->ihl*4);
/*取得UDP报头*/
app_data = p_udphdr + p_udphdr->len; /*获得UDP协议部分的应用数据地址*/
app_len = n - 16 - p_iphdr->ihl*4 - p_udphdr->len;
/*获得UDP协议部分的应用数据长度*/
}
printf("application data address:0x%x, length:%d/n",app_data,app_len); /*打印应用数据的地址和长度*/