C++实现发送和接收自定义类型的链路层数据帧——绑定,目的地址不同于接收网卡

一 实战前准备

1 准备两台虚拟机

A机配置

网卡

IP

MAC

enp0s3

192.168.0.110

08:00:27:60:7b:7f

enp0s8

192.168.0.104

08:00:27:87:45:35

B机配置

网卡

IP

MAC

enp0s3

192.168.0.120

08:00:27:0c:3b:d3

二 接收端

1 代码

#include <stdio.h>  
#include <string.h>  
#include <errno.h>  
#include <sys/types.h>   
#include <sys/socket.h>  
#include <netpacket/packet.h>  
#include <net/if.h>  
#include <net/if_arp.h>  
#include <sys/ioctl.h>  
#include <arpa/inet.h> //for htons
#include <netinet/if_ether.h>   //for ethhdr
#define LEN     60
void print_str16(unsigned char buf[], size_t len)  
{  
    int     i;  
    unsigned char   c;  
    if (buf == NULL || len <= 0)  
        return;  
    for (i = 0; i < len; i++) {  
        c = buf[i];  
        printf("%02x", c);  
    }  
    printf("\n");  
}  
void print_sockaddr_ll(struct sockaddr_ll *sa)  
{  
    if (sa == NULL)  
        return;  
    printf("sll_family:%d\n", sa->sll_family);  
    printf("sll_protocol:%#x\n", ntohs(sa->sll_protocol));  
    printf("sll_ifindex:%#x\n", sa->sll_ifindex);  
    printf("sll_hatype:%d\n", sa->sll_hatype);  
    printf("sll_pkttype:%d\n", sa->sll_pkttype);  
    printf("sll_halen:%d\n", sa->sll_halen);  
    printf("sll_addr:"); print_str16(sa->sll_addr, sa->sll_halen);  
}  
int main()  
{  
    int             result = 0, fd, n, count = 0;  
    char    buf[LEN];  
    struct sockaddr_ll      sa, sa_recv;  
    struct ifreq    ifr;  
    socklen_t       sa_len = 0;  
    char    if_name[] = "enp0s3";  
    struct ethhdr *eth; //定义以太网头结构体指针
  

    //create socket  
    fd = socket(PF_PACKET, SOCK_RAW, htons(0x8902));  
    if (fd < 0) {  
        perror("socket error\n");  
        return errno;  
    }  
    
    
    memset(&sa, 0, sizeof(sa));  
    sa.sll_family = PF_PACKET;  
    sa.sll_protocol = htons(0x8902);  
    
    // get flags   
    strcpy(ifr.ifr_name, if_name);  //必须先得到flags,才能再得到index
    result = ioctl(fd, SIOCGIFFLAGS, &ifr);  
    if (result != 0) {   
        perror("ioctl error, get flags\n");  
        return errno;  
    }        
    result = ioctl(fd, SIOCGIFINDEX, &ifr);        //get index  
    if (result != 0) {  
        perror("ioctl error, get index\n");  
        return errno;  
    }  
    sa.sll_ifindex = ifr.ifr_ifindex;  
    result = bind(fd, (struct sockaddr*)&sa, sizeof(struct sockaddr_ll));  //bind fd  
    if (result != 0) {  
        perror("bind error\n");  
        return errno;  
    }  
  
      //recvfrom  
    while (1) {  
        memset(buf, 0, sizeof(buf));  
        // 第5个和第6个参数没有用NULL,这样可以获得对端(发送端)的物理地址sockaddr_ll的内容
         n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&sa_recv, &sa_len);  
        //n = recvfrom(fd, buf, sizeof(buf), 0, NULL, NULL);    //如果不需要打印sa_recv内容,用NULL也可以
        if (n < 0) {  
            printf("sendto error, %d\n", errno);  
            return errno;  
        }  
        printf("******************* recvfrom msg %d ****************\n", ++count);  
        print_str16((unsigned char*)buf, n);     //打印数据帧的内容
        
        eth = (struct ethhdr*)buf;
        //从eth里提取目的mac、源mac、协议号
        printf("proto=0x%04x,dst mac addr:%02x:%02x:%02x:%02x:%02x:%02x\n", ntohs(eth->h_proto), eth->h_dest[0], eth->h_dest[1], eth->h_dest[2], eth->h_dest[3], eth->h_dest[4], eth->h_dest[5]);
        printf("proto=0x%04x,src mac addr:%02x:%02x:%02x:%02x:%02x:%02x\n", ntohs(eth->h_proto), eth->h_source[0], eth->h_source[1], eth->h_source[2], eth->h_source[3], eth->h_source[4], eth->h_source[5]);
        
        // 打印sockaddr_ll的内容
        print_sockaddr_ll(&sa_recv);  
        printf("sa_len:%d\n", sa_len);  
    }  
    return 0;  
}

2 编译运行

[root@localhost test]# g++ recv.cpp -o recv
[root@localhost test]# ./recv

三 发送端

1 代码

#include <stdio.h>  
#include <string.h>  
#include <errno.h>  
#include <sys/types.h>   
#include <sys/socket.h>  
#include <netpacket/packet.h>  
#include <net/if.h>  
#include <net/if_arp.h>  
#include <sys/ioctl.h>  
#include <arpa/inet.h> //for htons
  
#define LEN     60  
  
  
void print_str16(unsigned char buf[], size_t len)  
{  
    int     i;  
    unsigned char   c;  
    if (buf == NULL || len <= 0)  
        return;  
    for (i = 0; i < len; i++) {  
        c = buf[i];  
        printf("%02x", c);  
    }  
    printf("\n");  
}  
int main()  
{  
    int             result = 0;  
    int             fd, n, count = 3, nsend = 0;  //count表示发送3个数据包
    char    buf[LEN];  
    struct sockaddr_ll      sa;  
    struct ifreq    ifr;  
    char    if_name[] = "enp0s3";  //本机要发送数据的网卡名称
    //对应enp0s8,192.168.0.104的网卡  08:00:27:87:45:35
    char    dst_mac[6] = { 0x08,0x00,0x27,0x87,0x45,0x35 };   
    char    src_mac[6];  
    short   type = htons(0x8902);  
  
    memset(&sa, 0, sizeof(struct sockaddr_ll));  
    memset(buf, 0, sizeof(buf));  
  
    //创建套接字  
    fd = socket(PF_PACKET, SOCK_RAW, htons(0x8902));  
    if (fd < 0) {  
        printf("socket error, %d\n", errno);  
        return errno;  
    }  
  
    //获得网卡索引号  
    strcpy(ifr.ifr_name, if_name);  
    result = ioctl(fd, SIOCGIFINDEX, &ifr);  
    if (result != 0) {  
        printf("get mac index error, %d\n", errno);  
        return errno;  
    }  
    sa.sll_ifindex = ifr.ifr_ifindex;  //赋值给物理层地址
  
      //get mac  
    result = ioctl(fd, SIOCGIFHWADDR, &ifr);  
    if (result != 0) {  
        printf("get mac addr error, %d\n", errno);  
        return errno;  
    }  
    memcpy(src_mac, ifr.ifr_hwaddr.sa_data, 6);  
  
      //set buf  
    memcpy(buf, dst_mac, 6);  
    memcpy(buf + 6, src_mac, 6);  
    memcpy(buf + 12, &type, 2);  
  
    print_str16((unsigned char*)buf, sizeof(buf));  
    //sendto  
    while (count-- > 0) {  
        n = sendto(fd, buf, sizeof(buf), 0, (struct sockaddr *)&sa, sizeof(struct sockaddr_ll));  
        if (n < 0) {  
            printf("sendto error, %d\n", errno);  
            return errno;  
        }  
        printf("sendto msg %d, len %d\n", ++nsend, n);  
    }  
    return 0;  
}

2 运行

[root@localhost test]# g++ send.cpp -o send
[root@localhost test]# ./send
0800278745350800270c3bd3890200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
sendto msg 1, len 60
sendto msg 2, len 60
sendto msg 3, len 60

3 A机结果

A机没有收到数据包,这说明我们绑定enp0s3后,recv只等待接收发向enp0s3的数据帧,而send的数据帧是发向enp0s8的,因此recv收不到。

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的C++代码示例,用于实现数据帧的传输和处理接收到的数据: ```c++ #include <iostream> #include <vector> using namespace std; // 定义数据帧结构体 struct DataFrame { int len; // 数据长度 char* data; // 数据指针 }; // 数据帧发送函数 void sendData(DataFrame frame) { // 发送数据帧 // ... } // 数据帧处理函数 void processData(char* buffer, int bufferLen) { // 将接收到的数据 buffer 解析成数据帧 DataFrame frame; frame.len = buffer[0]; frame.data = &buffer[1]; // 处理数据帧 // ... } int main() { // 构造数据帧 DataFrame frame; frame.len = 5; frame.data = new char[5]; frame.data[0] = 'H'; frame.data[1] = 'e'; frame.data[2] = 'l'; frame.data[3] = 'l'; frame.data[4] = 'o'; // 发送数据帧 sendData(frame); // 模拟接收数据帧 char buffer[6] = { 5, 'W', 'o', 'r', 'l', 'd' }; processData(buffer, 6); // 释放内存 delete[] frame.data; return 0; } ``` 在上面的代码中,我们定义了一个数据帧的结构体 `DataFrame`,其中包含了数据的长度和数据的指针。我们还定义了两个函数,`sendData` 用于发送数据帧,`processData` 用于处理接收到的数据。 在 `main` 函数中,我们构造了一个数据帧 `frame`,并通过 `sendData` 函数将其发送出去。然后,我们模拟接收到一个数据帧,将其存储在 `buffer` 数组中,并通过 `processData` 函数对其进行解析和处理。 需要注意的是,在使用完数据帧后,我们需要释放数据指针所指向的内存,以避免内存泄漏。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值