繁体   English   中英

linux ARP接收信息

[英]linux ARP recvfrom information

如果我发送ARP程序包,我可以从recv找出发件人的IP地址是什么?之所以这样问,是因为我将多个程序包发送到带有子进程的不同主机,并且收到了所有子进程的响应,所以我问如果有办法知道哪个孩子寄了什么包裹。谢谢。

struct ether_arp req;
struct sockaddr_ll addr={0};
struct ifreq inter;
int sock;//I check usinginter if the interface is correct
sock=socket(AF_PACKET,SOCK_DGRAM,htons(ETH_P_ARP));
 if (sock==-1) {
 printf("%s",strerror(errno));
}
if (ioctl(sock,SIOCGIFINDEX,&inter)==-1) {
printf("%s",strerror(errno));
return ;//for the interface index
addr.sll_family=AF_PACKET;
addr.sll_ifindex=index;
addr.sll_halen=ETHER_ADDR_LEN;
addr.sll_protocol=htons(ETH_P_ARP);
memcpy(addr.sll_addr,ether_broadcast_addr,ETHER_ADDR_LEN);
req.arp_hrd=htons(ARPHRD_ETHER);
req.arp_pro=htons(ETH_P_IP);
req.arp_hln=ETHER_ADDR_LEN;
req.arp_pln=sizeof(in_addr_t);
req.arp_op=htons(ARPOP_REQUEST);
......................  
 memcpy(&req.arp_spa,&target_ip_addr.s_addr,sizeof(req.arp_spa));//this way I save the   source IP
.......
if (sendto(sock,&req,sizeof(req),0,(struct sockaddr*)&addr,sizeof(addr))==-1) {
printf("%s",strerror(errno));
}THis is how I send it

还有更多代码,但我认为这不相关

您不能使用recvfrom查找发件人的ip地址,因为ARP数据包没有网络层。

如果您想知道哪个主机(具有其相对的MAC地址和ip地址)对您的请求进行了回复,则必须解剖如下所示的数据包:

在此处输入图片说明

查找有关单个字段的更多信息: ARP消息格式

您要查找的32位在Sender Protocol Address

这是一个虚拟的代码段,显示了arp响应ARP请求的主机的ip地址。

免责声明:我没有测试过,但是应该可以给您一个想法。

/* buf is buffer containing the ethernet frame */
char buf[65535];

/* arp frame points to the arp data inside the ethernet frame */
struct ether_arp *arp_frame;

/* skipping the 14 bytes of ethernet frame header */
arp_frame = (struct ether_arp *) (buf + 14);

/* read until we got an arp packet or socket got a problem */
while (recv(sock, buf, sizeof(buf), 0))
{
    /* skip to the next frame if it's not an ARP packet */
    if ((((buf[12]) << 8) + buf[13]) != ETH_P_ARP) 
        continue;

    /* skip to the next frame if it's not an ARP REPLY */
    if (ntohs (arp_frame->arp_op) != ARPOP_REPLY)
        continue;

    /* got an arp reply! this is where i'm printing what you need             */
    /* ... and YES... spa of arp_spa field stands for Sender Protocol Address */
    printf("I got an arp reply from host with ip: %u.%u.%u.%u\n", arp_frame->arp_spa[0],
                                                                  arp_frame->arp_spa[1],
                                                                  arp_frame->arp_spa[2], 
                                                                  arp_frame->arp_spa[3]);

    /* break? */
    break;    
}

这是侦听ARP-REPLIES的小程序的完整工作示例。

arp-reply-catcher.c源码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM