【问题标题】:Mismatch in assigning IP address to a buffer and printing contents of buffer为缓冲区分配 IP 地址和打印缓冲区内容不匹配
【发布时间】: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


    【解决方案1】:

    第一个问题是你的内存分配

    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;
    

    我建议这个解决方案更容易;)

    【讨论】:

    • 最后一件事。我需要调用 CreateIpHeader(source_addr,dest_addr) 这个函数的参数类型是什么?
    • 对不起,我现在没有这个功能。如果你打算自己实现这个功能,你应该使用 in_addr_t (u_int32)。在函数内部,您必须通过调用 inet_addr() 以网络字节顺序转换您的地址
    猜你喜欢
    • 2016-12-25
    • 2013-09-26
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 2018-10-20
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多