我有以下簡單的代碼來捕獲發送到我設備的所有 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 :
uj5u.com熱心網友回復:
的字串,要被列印用%s,是序列字符與特殊空終止字符終止'\0'。
輸入的資料e->ether_shost是一串六個位元組,不是字符,不是空終止符,需要將它們一個一個列印為小整數(通常是十六進制表示法):
printf("hhx:hhx:hhx:hhx:hhx:hhx\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]);
有關所用格式的說明,請參見例如此printf參考資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/373208.html
上一篇:C客戶端未從服務器接收
