我在C中实现原始套接字。在下面的代码中,我正在解析从发送方收到的IP头。
a. I will send back the ack as well so storing IP address received in a buffer(ret_ip).
b. I don't have another computer so using lo (local loop back) as my interface.
//first two printf statements are printing the right address, 10.100.207.74
//daddr SENT = 32.112.247.9saddr SENT = 36.112.247.9
我怎样才能正确理解? 我认为这个问题是由于memcpy的第一个参数指向unsigned char而第二个参数指向_be32。
我在程序中实际想做的是:ret_ip的前4个字节应包含目标地址,接下来4个包含源地址。然后我将创建IP头并使dest addr = source addr和source-addr = dest-addr。并向发送者发送ACK。
char* ParseIPHeader(unsigned char *packet,int len)
{
struct ethhdr *ethernet_header;
struct iphdr *ip_header;
char *ret_ip;
ethernet_header=(struct ethhdr *)packet;
if(ntohs(ethernet_header->h_proto)==ETH_P_IP)
{
if(len>=(sizeof(struct ethhdr)+sizeof(struct iphdr)))
{
ip_header=(struct iphdr*)(packet+sizeof(struct ethhdr));
ret_ip=malloc(2*(sizeof(ip_header->daddr)));
printf("Dest IP address: %s\n",inet_ntoa(ip_header->daddr));
printf("Source IP address: %s\n",inet_ntoa(ip_header->saddr));
memcpy(ret_ip,&(ip_header->daddr),sizeof(ip_header->daddr));
memcpy(ret_ip+4,&(ip_header->saddr),4);
printf("daddr SENT = %s",inet_ntoa(ret_ip));
printf("saddr SENT = %s",inet_ntoa(ret_ip+4));
}
else
printf("IP packet does not have full header\n");
}
else
{
//not an IP packet
}
return ret_ip;
}
谢谢:)
答案 0 :(得分:0)
第一个问题是你的记忆分配
ret_ip=malloc(2*(ip_header->daddr));
应该是
ret_ip=malloc(2*(sizeof(ip_header->daddr)));
但为什么你不再使用ip_hdr结构?例如
struct iphdr *ret_ip = malloc(sizeof(iphdr));
ret_ip->daddr = ip_header->saddr;
ret_ip->saddr = ip_header->daddr;
我建议这个解决方案更容易;)