【问题标题】:can't read arp packets in c无法在c中读取arp数据包
【发布时间】:2022-01-09 20:31:56
【问题描述】:

我有以下简单的代码来捕获发送到我的设备的所有 arp 数据包,但它不打印任何内容

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <net/ethernet.h>

int main(){
        int sock;
        char recvbuf[2048];
        if((sock=socket(PF_PACKET,SOCK_DGRAM,htons(ETH_P_ARP)))==-1){
                perror("socket error");
                return -1;
        }
        for(;;){
                if(recvfrom(sock,recvbuf,sizeof(recvbuf),0,NULL,NULL)==-1){
                        perror("recvfrom error");
                }
                struct ether_header *e;
                e=(struct ether_header *)recvbuf;
                printf("arp from :%s\n",e->ether_shost);
        }
}

输出如下:

arp from :
arp from :
arp from :
arp from :
arp from :

【问题讨论】:

  • e-&gt;ether_shost 是字节序列,而不是 ascii 字符(因此 %s 不合适)。尝试以十六进制显示它们中的每一个。
  • ether_shost 不是字符串,它是字节形式的以太网地址。
  • 我不明白这是字节数组与字符串不一样
  • 哦,好的,我现在明白了,我必须以十六进制分别打印每个字节

标签: c sockets raw-sockets


【解决方案1】:

要以%s 打印的字符串是一个以特殊空终止符'\0' 结尾的字符 序列。

e-&gt;ether_shost中的数据是一串六个字节,不是字符,不是以null结尾的,需要一个一个的打印成小整数(一般是十六进制):

printf("%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx\n",
    e->ether_shost[0], e->ether_shost[1], e->ether_shost[2],
    e->ether_shost[3], e->ether_shost[4], e->ether_shost[5]);

有关所使用格式的说明,请参见例如this printf reference.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多