首页 > 解决方案 > Linux下抓包时IP地址相同(C程序)

问题描述

我通过在 c 中编写代码来接收网络数据包。到目前为止,我可以正确接收数据包,但我面临的唯一问题是以太网、TCP 和 UDP 的 IP 地址相同。通过 tcpdump 接收时我没有遇到任何问题。

我的系统的以太网源是:b0:10:41:fc:d7:2f
我的接口的IP地址是:192.168.10.145

这些是接收到的数据包:

162 >>> 接收到的 66 字节数据包:以太网 src:b0:10:41:fc:d7:2f dst:b0:10:41:fc:d7:2f 类型:0x800 IP 版本:4 ihl:5 ttl:64协议:6 src:192.168.10.145 dst 192.168.10.145 TCP src:46888 dst:80 seq:3048209837 胜利:4508 ACK 000000:b728 0050 b5af fdad 0e1d 21a1(8010 119 ......! .. 0x0010:e258 0000 0101 080a 5a05 1f81 0595 4669

163 >>> 接收到的 66 字节数据包:以太网 src:b0:10:41:fc:d7:2f dst:b0:10:41:fc:d7:2f 类型:0x800 IP 版本:4 ihl:5 ttl:64协议:6 src:192.168.10.145 dst 192.168.10.145 TCP src:38836 dst:443 seq:1969857171 胜利:341 ACK 000000:97b4 01bb 7569 a293 0473 15bc 8010 ........ 0.... U 0x0010:11f1 0000 0101 080a 4011 29b5 45f5 c4da

164 >>> 接收到的 1024 字节数据包:以太网 src:0:1a:a0:3f:d6:fc dst:0:1a:a0:3f:d6:fc 类型:0x800 IP 版本:4 ihl:5 ttl:64协议:6 src:110.93.233.24 dst 110.93.233.24 TCP src:80 dst:46888 seq:236790177 win:595 ACK 000000:0050 b728 0e1d 21a1 b5af fdad 8010 0253 ........( .S 0x0010: 6e5f 0000 0101 080a 0595 46a1 5a05 199a n_........FZ.. 0x0020: f107 eb73 1b82 1492 c88f e84c 101a 9416 ...s.......L.... 0x0030: 9a27 900f 2020 1985 836f 79d5 8a26 15fa .'.. ...oy..&..

这是我的代码:

layer2: {
struct ethhdr *eth = (struct ethhdr*) data;
printf("\tEthernet src: %s dst: %s type: %#04x\n",
    ether_ntoa((const struct ether_addr*) eth->h_source),
    ether_ntoa((const struct ether_addr*) eth->h_dest),
    ntohs(eth->h_proto)
);
protocol = ntohs(eth->h_proto);
next_hdr = (char *) (eth + 1);}

layer3: switch (protocol) {
    case ETH_P_IP: {
        /* Parse IP protocol */
        struct iphdr *ip = (struct iphdr*) next_hdr;
        char buf[32];
        printf("\tIP version: %u ihl: %u ttl: %u protocol: %u src: %s dst %s\n",    
            ip->version,
            ip->ihl,
            ip->ttl,
            ip->protocol,
            inet_ntop(AF_INET, &ip->saddr, buf, sizeof(buf)),
            inet_ntop(AF_INET, &ip->daddr, buf, sizeof(buf))
        );

我究竟做错了什么 ?

标签: cpacket-sniffers

解决方案


您使用相同buf的方法来保存两个 IP 地址:

inet_ntop(AF_INET, &ip->saddr, buf, sizeof(buf)),
inet_ntop(AF_INET, &ip->daddr, buf, sizeof(buf))

因为您使用的是同一个缓冲区,并且两次调用inet_ntop()都在调用之前完成printf(),所以最后一次调用inet_ntop()将覆盖第一次调用的结果。


推荐阅读