【发布时间】:2014-05-30 20:18:24
【问题描述】:
我在 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;
}
谢谢:)
【问题讨论】:
标签: c ip-address memcpy raw-sockets