【问题标题】:Why does this code produce an incomplete IP address?为什么此代码会产生不完整的 IP 地址?
【发布时间】:2013-08-01 23:18:04
【问题描述】:

我正在使用以下代码从套接字(AF_PACKET、SOCK_DGRAM、htons(ETH_P_ARP))读取缓冲区。我正在使用 arp_frame 结构来访问包含的 ARP 回复的组成部分。 inet_ntoa() 返回 IP 的正确第一个八位字节,但其他八位字节为 0,生成 172.0.0.0。

问题 1 是为什么会发生这种情况? 问题 2 是如何按主机字节顺序将 msg 缓冲区的 r 字节打印为十六进制来调试数据包?

    unsigned char msg[65535];
    struct ether_arp *arp_frame = (struct ether_arp *)msg;

    while ((r = recv(sock, msg, sizeof(msg), 0))) {
            // skip it's not an ARP REPLY
            if (ntohs(arp_frame->arp_op) != ARPOP_REPLY)
                    continue;

            for (i = 0; i < SONOS_PREFIX_NUM; i++) {
                    if (!memcmp(sonos_prefixes[i], arp_frame->arp_sha, 3)) {
                            struct in_addr addr;
                            addr.s_addr = *arp_frame->arp_spa;

                            printf("Blah: %lu\n", ntohl(*arp_frame->arp_spa));
                            printf("Sonos found at %s\n", inet_ntoa(addr));
                    }
            }
    }

【问题讨论】:

    标签: c arp


    【解决方案1】:

    struct ether_arp 看起来像这样:

    struct  ether_arp {
        struct  arphdr ea_hdr;          /* fixed-size header */
        u_int8_t arp_sha[ETH_ALEN];     /* sender hardware address */
        u_int8_t arp_spa[4];            /* sender protocol address */
        u_int8_t arp_tha[ETH_ALEN];     /* target hardware address */
        u_int8_t arp_tpa[4];            /* target protocol address */
    };
    

    考虑到这一点,我认为您的addr.s_addr = *arp_frame-&gt;arp_spa; 看起来有点可疑。 arp_frame-&gt;arp_spa 产生一个u_int8_t[4],然后您将其作为指针取消引用。我认为memcpy() 在那里可能更合适。

    【讨论】:

    • 大喊大叫。似乎我完全查阅了错误的手册,因为它说它是 u_long - propox.com/download/edunet_doc/all/html/structether__arp.html。谢谢:)
    • 这可能取决于平台...在不需要字节反转的大端系统上,它可以方便地存储为 32 位整数,但在小端系统上,我想这将取决于ntohl() 的实现以及实现者选择的朋友......即使它是一个无符号整数/长整数,但将其视为指针是不对的......
    【解决方案2】:

    如果您认为 API 已损坏,请打印出字节。

    “我想,布鲁图斯,错不在星星上。”

    【讨论】:

    • 您会看到我正在过滤以确保这些是回复。我还应该注意,这是源地址,而不是目标地址,并且代码为所有解析的 ARP 回复生成 172.0.0.0。
    • 现在已经看到了正确答案,这个答案中唯一有用的部分是“如果您认为 API 已损坏,请打印出字节。”
    猜你喜欢
    • 2012-01-03
    • 2018-10-14
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多