linux C++ ARP本地局域网发送及接收

本文介绍了一种在Linux环境下使用C++实现ARP协议进行本地局域网内的数据发送和接收的方法。测试环境为Fedora 32,GCC 10.1.1。程序运行需root权限,存在接收包时未过滤导致重复现象的问题。通过每500ms发送一个ARP请求并使用新线程接收回应,以避免设备因大量包处理而不响应的情况。源代码可在GitHub找到。
摘要由CSDN通过智能技术生成

代码

#include <iostream>
#include <cstring>
#include <unistd.h>
#include <netdb.h>
#include <errno.h>
#include <thread>

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>

#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <sys/ioctl.h>

using namespace std;

//#define NETWORK_DEVICE_NAME "wlp3s0"
#define uchar unsigned char

struct arp_packet{
   
    //first layer
    char dest_MAC[6];
    char srce_MAC[6];
    uchar type[2];

    //second layer
    uchar hw_t[2];
    uchar protocol_t[2];
    uchar hw_size;
    uchar protocol_size;
    uchar opcode[2];

    char src_MAC[6];
    u_int32_t src_IP;
    char dst_MAC[6];
    u_int32_t dst_IP;

    //char padding[18];
};

extern int h_errno;
extern int errno;
static int sent_num = 0;   //number of sent arp packets

void recv_cout(int recv_socket){
   
    unsigned char buf[80];
    memset(buf, 0, 80);

    struct in_addr convert;

    arp_packet* tmp_packet = nullptr;

    struct timeval tv = {
   255, 0};      //set receive timeout 255s
    if(setsockopt(recv_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0){
   
        cout << "ERROR: failed to set socket receive timeout" << endl;
        cout << strerror(errno) << endl;
    }

    for(int i 
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值