我正在用 C 实现原始套接字。在下面的代码中,我正在解析从发件人收到的 IP header 。
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 header 并使 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;
}
谢谢 :)
最佳答案
第一个问题是你的内存分配
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;
我建议这个解决方案更容易;)
关于c - 将 IP 地址分配给缓冲区和打印缓冲区内容不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23101313/