【RawSocket】RawSocket是什么?

1.RawSocket简介

RawSocket是数据链路层的socket

Raw socket(原始套接字)是一种特殊的网络套接字类型,它允许应用程序直接发送和接收底层的网络数据包,而不需要经过标准的传输层协议(如TCP或UDP)的处理。以下是raw socket的一些关键特点:

  1. 直接访问网络层
  • Raw socket允许应用程序直接与网络层交互,发送和接收IP数据包。这意味着应用程序可以绕过传输层协议,直接处理网络数据。

2.灵活性

  • 由于raw socket提供了对网络数据包的直接控制,它为网络编程提供了极大的灵活性。应用程序可以自定义数据包的内容和格式,实现特定的网络功能。

3.低级访问

  • Raw socket提供了对网络协议栈的低级访问。应用程序可以访问和修改IP头、TCP头、UDP头等网络协议头部,实现复杂的网络操作。

4.安全性

  • Raw socket的使用需要较高的权限,通常只有具有管理员权限的用户才能创建raw socket。这是因为raw socket可以发送任意类型的网络数据包,可能会被用于恶意目的。

5.应用场景

  • Raw socket常用于网络工具和诊断工具的开发,如网络嗅探器、防火墙、入侵检测系统等。它们需要直接访问网络数据包来实现特定的功能。

6.编程复杂性

  • 由于raw socket提供了底层的网络访问,使用raw socket进行网络编程通常比使用标准的套接字更加复杂。开发者需要对网络协议有深入的理解。

7.操作系统支持

  • 不同的操作系统对raw socket的支持程度不同。大多数Unix-like系统(如Linux和macOS)支持raw socket,但可能需要特定的权限或配置

2.raw socket收发底层网络数据包

2.1 创建raw socket

创建一个raw socket:

int sock = socket(PF_PACKET,SOCK_RAW,htons(ETH_P_ALL));
if(sock < 0)
{
	perror("sock");
	return -1;
}

在Linux系统中,使用 socket函数创建原始套接字(raw socket)时,可以捕获和发送任意类型的网络数据包。以下是 socket函数调用 socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));中各个参数的说明:

1.PF_PACKET

  • PF_PACKET(Packet Family)是一个常量,表示要创建的套接字用于处理原始数据包。这个参数指定了套接字的地址族,告诉内核这个套接字将用于处理低级的数据包。

2.SOCK_RAW

  • SOCK_RAW是一个常量,表示套接字类型为原始套接字。这种类型的套接字允许应用程序直接发送和接收原始的网络数据包,绕过标准的传输层协议(如TCP或UDP)。

3.htons(ETH_P_ALL)

  • htons是“host to network short”的缩写,是一个函数,用于将16位的主机字节顺序值转换为网络字节顺序。这对于网络通信是必要的,因为网络协议要求使用大端字节顺序。
  • ETH_P_ALL是一个宏,定义了以太网协议类型,其值是0x0003。使用 htons(ETH_P_ALL)表示这个原始套接字将捕获所有类型的以太网数据包,无论它们的协议类型是什么。
此外还有以下宏定义:
ETH_P_IP:表示 IPv4 协议,即以太网帧包含一个 IP 数据包。
ETH_P_ARP:表示 ARP(地址解析协议)数据包,用于将网络层的 IP 地址解析为链路层的 MAC 地址。
ETH_P_RARP:表示 RARP(反向地址解析协议),用于将链路层的 MAC 地址解析为网络层的 IP 地址。这个协议现在已经很少使用,被 DHCP 所取代。
ETH_P_IPV6:表示 IPv6 协议,即以太网帧包含一个 IPv6 数据包。
ETH_P_8021Q:表示 802.1Q VLAN(虚拟局域网)标记的以太网帧。
ETH_P_PPP_DISC:表示 PPPoE(以太网上的 PPP)发现阶段的数据包。
ETH_P_PPP_SES:表示 PPPoE 会话阶段的数据包。
ETH_P_MPLS_UC:表示 MPLS(多协议标签交换)单播数据包。
ETH_P_MPLS_MC:表示 MPLS 多播数据包。
ETH_P_802_3:表示标准的以太网帧,不包含任何额外的协议信息。

2.2 发送数据包

2.2.1 发送数据包函数原型

int sendto(int s,const void *buf,int len,unsigned int flags,
	const struct sockaddr *to,int tolen);

2.2.2 返回值

成功则返回实际传送出去的字符数,失败返回-1,错误原因会存在于errno中

2.2.3 参数说明

s:socket描述符;

buf:rawsocket数据包缓存区(包含待发送数据)

len:rawsocket数据包的长度

flags:调用方式标志位(一般设置为0)

to:指向接收数据的主机地址信息的结构体(sockaddr_in需要进行类型转换)

tolen: to所指结构体的长度

2.2.4 使用方法

struct sockaddr_ll sll;
memset(&sll,0,sizeof(sll));
sll.sll_ifindex = 2;     // 指定网卡
if(sendto(sock,packet_start,sizeof(packet_start),0,&sll,sizeof(sll)) < 0)
{
	perror("sendto");
	return 1;
}

sendto发送原始数据包,只需用struct sockaddr_ll的sll_ifindex指定网卡。

2.2.5 代码实例

发送raw socket(rawsocket_send.c):

#include <sys/socket.h>  
#include <string.h>  
#include <sys/types.h>  
#include <arpa/inet.h>  
#include <features.h>    /* for the glibc version number */  
#include <asm/types.h>  
#include <linux/if_packet.h>  
#include <linux/if_ether.h>   /* The L2 protocols */  
#include <stdio.h>  
#include <netinet/in.h>  
#include <net/if.h>  
#include <sys/ioctl.h>  
#include <errno.h>  
  
#define _PATH_PROCNET_DEV               "/proc/net/dev"  
  
static char *get_name(char *name, char *p)  
{  
    while (isspace(*p))  
            p++;  
  
    while (*p) {  
            if (isspace(*p))  
        break;  
            if (*p == ':') {    /* could be an alias */  
        char *dot = p, *dotname = name;  
        *name++ = *p++;  
        while (isdigit(*p))  
        *name++ = *p++;  
        if (*p != ':') {    /* it wasn't, backup */  
        p = dot;  
        name = dotname;  
        }  
        if (*p == '\0')  
        return NULL;  
        p++;  
        break;  
    }  
    *name++ = *p++;  
    }  
    *name++ = '\0';  
    return p;  
}  
  
/** 
 * read_netdev_proc - read net dev names form proc/net/dev 
 * @devname: where to store dev names, devname[num][len] 
 */  
static int read_netdev_proc(void *devname, const int num, const int len)  
{  
    FILE *fh;  
    char buf[512];  
        int cnt = 0;  
        char *dev = (char *)devname;  
  
        if(devname == NULL || num < 1 || len < 4){  
            printf("read_netdev_proc: para error\n");  
            return -1;  
        }  
  
        memset(devname, 0, len * num);  
  
    fh = fopen(_PATH_PROCNET_DEV, "r");  
    if (!fh) {  
        fprintf(stderr, "Warning: cannot open %s (%s). Limited output.\n",  
            _PATH_PROCNET_DEV, strerror(errno));   
        return -1;  
      }  
  
    fgets(buf, sizeof buf, fh); /* eat two line */  
    fgets(buf, sizeof buf, fh);  
  
        cnt = 0;  
    while (fgets(buf, sizeof buf, fh) && cnt < num) {  
            char *s, name[IFNAMSIZ];  
            s = get_name(name, buf);  
  
            strncpy(devname, name, len);  
            devname += len;  
            printf("get_name: %s\n", name);  
    }  
  
    if (ferror(fh)) {  
            perror(_PATH_PROCNET_DEV);  
    }  
  
    fclose(fh);  
    return 0;  
}  
  
/** 
 * get_hwaddr - get netdevice mac addr  
 * @name: device name, e.g: eth0 
 * @hwaddr: where to save mac, 6 byte hwaddr[6] 
 * @return: 0 on success, -1 on failure 
 */  
int get_hwaddr(char *name, unsigned char *hwaddr)  
{  
    struct ifreq ifr;  
    unsigned char memzero[6];  
    int sock;  
  
    if(name == NULL || hwaddr == NULL){  
        printf("get_hwaddr: NULL para\n");  
        return -1;  
    }  
  
 sock = socket(AF_INET, SOCK_STREAM, 0);  
    if(sock < 0){  
        printf("get_hwaddr: socket error\n");  
        //return -1;  
    }  
  
    //get eth1 mac addr  
    memset(hwaddr, 0, 6);  
    memset(&ifr, 0, sizeof(ifr));  
    strncpy(ifr.ifr_name, name, 6);  
    if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0){  
            perror("get_hwaddr ioctl:");  
            close(sock);  
            return -1;  
    } else {  
            memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, 6);  
            //printf("hwaddr: %2x : %2x : %2x : %2x : %2x : %2x\n", hwaddr[0], hwaddr[1],hwaddr[2], hwaddr[3],hwaddr[4], hwaddr[5]);  
    }  
  
    memset(memzero, 0, 6);  
    if(memcmp(memzero, hwaddr, 6) == 0){  
        printf("no mac\n");  
        return -1;  
    }  
  
    close(sock);  
    return 0;  
}  
  
unsigned char packet_start[]={  
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff,//dst mac  
    0x00, 0x23, 0x54, 0x0e, 0xe5, 0xd8,//src mac  
    0x88, 0x8e, //Type: 802.1x authentication  
        0x01, //Version:v1  
        0x01, //Type:  Start (1)  
        0x00, 0x00//Length 0  
};  
  
void printhex(void *hex, int len, char *tag)  
{  
    int i;  
    unsigned char *p = (unsigned char *)hex;  
  
    if(len < 1)  
        return;  
  
    for(i = 0; i < len - 1; i++){  
        if(*p < 0x10)  
            printf("0%x%s", *p++, tag);  
        else  
            printf("%2x%s", *p++, tag);  
    }  
  
    if(*p < 0x10)  
        printf("0%x\n", *p++);  
    else  
        printf("%2x\n", *p++);  
}  
  
int main(int argc, char **argv)  
{  
    int i;  
    unsigned char hwaddr[6];  
    char devname[3][7];  
    unsigned char buf[1024]; // for revevied packet  
    int ret;  
  
    read_netdev_proc(devname, 3, 7);  
  
    for(i = 0; i < 3 && get_hwaddr(devname[i], hwaddr) != 0; i++){   
        //empty  
    }  
  
    printf("devname: [ %s ]\t", devname[i]);  
    printhex(hwaddr, 6, ":");  
  
    int sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));  
    if(sock < 0){  
        perror("sock");  
        return -1;  
    }  
  
    struct sockaddr_ll sll;  
    memset(&sll, 0, sizeof(sll));  
    sll.sll_ifindex = 2; // It seems only need this to specify whiAWSch NIC to use  
  
    memcpy(packet_start + 6, hwaddr, 6);  
    while(1){  
        if (sendto(sock, packet_start, sizeof packet_start, 0, &sll, sizeof(sll)) < 0){  
            perror("sendto");  
            return 1;  
        }  
        printf("Sendto Success!\n");  
        sleep(1);  
    }  
    close(sock );
    return 0;  
}  

2.3 接收数据包

2.3.1 接收数据包函数原型

int recvfrom(int s,void *buf,int len,unsigned int flags,
		struct sockaddr *from,int *fromlen)

2.3.2 返回值

成功则返回实际接收到的字符数,失败返回-1,错误原因存于errno中。

2.3.3 参数说明

s: socket描述符

buf: rawsocket数据报缓存区(包含所接收的数据)

len: 缓冲区长度

flags: 调用操作方式(一般设置为0)

from:指向发送数据的客户端地址信息的结构体(sockaddr_in需类型和转换)

fromlen:指针,指向from结构体长度值

2.3.4 使用方法

ret  = recvfrom(sock,buf,1024,0,NULL,NULL);

2.3.5 代码示例

接收raw socket(rawsocket_recv.c):

#include <sys/socket.h>  
#include <string.h>  
#include <sys/types.h>  
#include <arpa/inet.h>  
#include <features.h>    /* for the glibc version number */  
#include <asm/types.h>  
#include <linux/if_packet.h>  
#include <linux/if_ether.h>   /* The L2 protocols */  
#include <stdio.h>  
#include <netinet/in.h>  
#include <net/if.h>  
#include <sys/ioctl.h>  
#include <errno.h>  

void printhex(void *hex, int len, char *tag)  
{  
    int i;  
    unsigned char *p = (unsigned char *)hex;  
  
    if(len < 1)  
        return;  
  
    for(i = 0; i < len - 1; i++){  
        if(*p < 0x10)  
            printf("0%x%s", *p++, tag);  
        else  
            printf("%2x%s", *p++, tag);  
    }  
  
    if(*p < 0x10)  
        printf("0%x\n", *p++);  
    else  
        printf("%2x\n", *p++);  
}  
  
int main(int argc, char **argv)  
{  
    int i;  
    unsigned char hwaddr[6];  
    char devname[3][7];  
    unsigned char buf[1024]; // for revevied packet  
    int ret;  

    int sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));  
    if(sock < 0){  
        perror("sock");  
        return -1;  
    }  

    while(1){  
        ret = recvfrom(sock, buf, 1024, 0, NULL, NULL);  
 
        printf("recv: ");  
        printhex(buf, ret, " ");  
    }  
    close(sock );
    return 0;  
}  

将以上两份代码编译生成两个可执行程序:

gcc rawsocket_send.c -o rawsocket_send
gcc rawsocket_recv.c -o rawsocket_recv

手动执行收发程序:

sudo ./rawsocket_send
sudo ./rawsocket_recv

2.4 收发实例运行

发送端

image

接收端

image

wireshark抓取报文

image

3.rawSocket进行文件收发

3.1 rawSocket发送指定路径的文件

rawsocket.h

#ifndef _RAWSOCKET_H_
#define _RAWSOCKET_H_

//#include <sys/socket.h>  
#include <string.h>  
#include <sys/types.h>  
//#include <arpa/inet.h>  
#include <features.h>    /* for the glibc version number */  
#include <asm/types.h>  
#include <linux/if_packet.h>  
#include <linux/if_ether.h>   /* The L2 protocols */  
#include <stdio.h>  
//#include <netinet/in.h>  
//#include <net/if.h>  
#include <sys/ioctl.h>  
#include <errno.h>  
#include <stdlib.h>
#include <signal.h>
#include <linux/if_packet.h>
#include <linux/if.h>


#define SRCMAC_LEN    6
#define DSTMAC_LEN    6
#define PROTOTYPE_LEN    2


unsigned char packet_start[]={  
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff,//dst mac  
    0x00, 0x23, 0x54, 0x0e, 0xe5, 0xd8,//src mac  
    0x88, 0x8e, //Type: 802.1x authentication  
        0x01, //Version:v1  
        0x01, //Type:  Start (1)  
        0x00, 0x00//Length 0  
};  

unsigned char packet_type[]={ 
    0x08,0x06, //Type: 802.1x authentication  
};


#endif

rawsocket_sendfile.c

#include "rawsocket.h"  

  
#define _PATH_PROCNET_DEV               "/proc/net/dev"  
  
static char *get_name(char *name, char *p)  
{  
    while (isspace(*p))  
            p++;  
  
    while (*p) {  
            if (isspace(*p))  
        break;  
            if (*p == ':') {    /* could be an alias */  
        char *dot = p, *dotname = name;  
        *name++ = *p++;  
        while (isdigit(*p))  
        *name++ = *p++;  
        if (*p != ':') {    /* it wasn't, backup */  
        p = dot;  
        name = dotname;  
        }  
        if (*p == '\0')  
        return NULL;  
        p++;  
        break;  
    }  
    *name++ = *p++;  
    }  
    *name++ = '\0';  
    return p;  
}  
  
/** 
 * read_netdev_proc - read net dev names form proc/net/dev 
 * @devname: where to store dev names, devname[num][len] 
 */  
static int read_netdev_proc(void *devname, const int num, const int len)  
{  
    FILE *fh;  
    char buf[512];  
    int cnt = 0;  
    char *dev = (char *)devname;  
  
    if(devname == NULL || num < 1 || len < 4){  
        printf("read_netdev_proc: para error\n");  
        return -1;  
    }  
  
    memset(devname, 0, len * num);  
  
    fh = fopen(_PATH_PROCNET_DEV, "r");  
    if (!fh) {  
        fprintf(stderr, "Warning: cannot open %s (%s). Limited output.\n",  
            _PATH_PROCNET_DEV, strerror(errno));   
        return -1;  
      }  
  
    fgets(buf, sizeof buf, fh); /* eat two line */  
    fgets(buf, sizeof buf, fh);  
  
    cnt = 0;  
    while (fgets(buf, sizeof buf, fh) && cnt < num) {  
            char *s, name[IFNAMSIZ];  
            s = get_name(name, buf);  
  
            strncpy(devname, name, len);  
            devname += len;  
            printf("get_name: %s\n", name);  
    }  
  
    if (ferror(fh)) {  
            perror(_PATH_PROCNET_DEV);  
    }  
  
    fclose(fh);  
    return 0;  
}  
  
/** 
 * get_hwaddr - get netdevice mac addr  
 * @name: device name, e.g: eth0 
 * @hwaddr: where to save mac, 6 byte hwaddr[6] 
 * @return: 0 on success, -1 on failure 
 */  
int get_hwaddr(char *name, unsigned char *hwaddr)  
{  
    struct ifreq ifr;  
    unsigned char memzero[6];  
    int sock;  
  
    if(name == NULL || hwaddr == NULL){  
        printf("get_hwaddr: NULL para\n");  
        return -1;  
    }  
  
    sock = socket(AF_INET, SOCK_STREAM, 0);  
    if(sock < 0){  
        printf("get_hwaddr: socket error\n");  
        //return -1;  
    }  
  
    //get eth1 mac addr  
    memset(hwaddr, 0, 6);  
    memset(&ifr, 0, sizeof(ifr));  
    strncpy(ifr.ifr_name, name, 6);  
    if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0){  
            perror("get_hwaddr ioctl:");  
            close(sock);  
            return -1;  
    } else {  
            memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, 6);  
            //printf("hwaddr: %2x : %2x : %2x : %2x : %2x : %2x\n", hwaddr[0], hwaddr[1],hwaddr[2], hwaddr[3],hwaddr[4], hwaddr[5]);  
    }  
  
    memset(memzero, 0, 6);  
    if(memcmp(memzero, hwaddr, 6) == 0){  
        printf("no mac\n");  
        return -1;  
    }  
  
    close(sock);  
    return 0;  
}  
  

  
void printhex(void *hex, int len, char *tag)  
{  
    int i;  
    unsigned char *p = (unsigned char *)hex;  
  
    if(len < 1)  
        return;  
  
    for(i = 0; i < len - 1; i++){  
        if(*p < 0x10)  
            printf("0%x%s", *p++, tag);  
        else  
            printf("%2x%s", *p++, tag);  
    }  
  
    if(*p < 0x10)  
        printf("0%x\n", *p++);  
    else  
        printf("%2x\n", *p++);  
}  
  
int main()  
{  
    int i;  
    unsigned char hwaddr[SRCMAC_LEN];
    unsigned char hwaddr_dst[DSTMAC_LEN] = {0x54,0x6C,0xEB,0x2D,0x3D,0xC2};  
    char devname[3][7];  
    int ret;  
  
    read_netdev_proc(devname, 3, 7);  
  
    for(i = 0; i < 3 && get_hwaddr(devname[i], hwaddr) != 0; i++){   
        //empty  
    }  
  
    printf("devname: [ %s ]\t", devname[i]);  
    printhex(hwaddr, 6, ":");  

#if 0
    int sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));  
    if(sock < 0){  
        perror("sock");  
        return -1;  
    }  
  
    struct sockaddr_ll sll;  
    memset(&sll, 0, sizeof(sll));  
    sll.sll_ifindex = 2; // It seems only need this to specify whiAWSch NIC to use  
#else
    struct sockaddr_ll sll;
    memset(&sll,0,sizeof(sll));
    sll.sll_family    = AF_PACKET;//填写AF_PACKET,不再经协议层处理
    sll.sll_protocol  = htons(ETH_P_ALL);

#if 0
    struct ifreq req;
    int sd;
    sd = socket(PF_INET,SOCK_DGRAM,0);   //这个sd就是用来获取eth0的index,完了就关闭
    strncpy(req.ifr_name,"enp0s3",4);      //通过设备名称获取index
    ret=ioctl(sd,SIOCGIFINDEX,&req);
  
    close(sd);
    if (ret==-1)
    {
        printf("Level:%d [Searcher main]Get eth0 index err \n", ret);
    }
#endif 

    sll.sll_ifindex   = 2;                  //网卡eth0的index,非常重要,系统把数据往哪张网卡上发,就靠这个标识
    sll.sll_pkttype   = PACKET_OUTGOING;   //标识包的类型为发出去的包

    // 以下配置非必须
    sll.sll_halen     = DSTMAC_LEN;                 //目标MAC地址长度为6
    //填写目标MAC地址
    sll.sll_addr[0]   = 0x54;
    sll.sll_addr[1]   = 0x6C;
    sll.sll_addr[2]   = 0xEB;
    sll.sll_addr[3]   = 0x2D;
    sll.sll_addr[4]   = 0x3D;
    sll.sll_addr[5]   = 0xC2;

#endif

    long bufSize = 0;  
  
    FILE* readfile = fopen("/home/user/Desktop/codes/my_em/my-embedded/app/NET/RawSocket/filename.txt","rb");

    if(!readfile)
    {
        perror("file open failed:\n");
        return -1;
    }

    // get file size
    fseek(readfile,0,SEEK_END);  // 将文件位置指针移动到最后
    bufSize = ftell(readfile);   // ftell(FILE *stream):返回给定流stream的当前文件位置,获取当前位置相对文件首的位移,位移值等于文件所含字节数
    fseek(readfile,0,SEEK_SET);      // 将文件位置指针移动到开头
    printf("filesize:%ld\n",bufSize);

   // unsigned char buffer[1024] = {0};
    unsigned char *buffer = (unsigned char*)malloc(sizeof(unsigned char)*bufSize+8);
    if(!buffer)
    {
        return -1;
    }
  
    // dst mac:6  src mac:6  
    memcpy(buffer,hwaddr_dst,DSTMAC_LEN);                             // dst mac
    memcpy(buffer+DSTMAC_LEN,hwaddr,SRCMAC_LEN);                      // src mac
    memcpy(buffer+DSTMAC_LEN+SRCMAC_LEN,packet_type,PROTOTYPE_LEN);   // proto type
  

    int sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));  
    if(sock < 0){  
        perror("sock");  
        return -1;  
    } 

    int nCount;
    while((nCount = fread(&buffer[DSTMAC_LEN+SRCMAC_LEN+PROTOTYPE_LEN],1,bufSize,readfile)) > 0)
    {
        if (sendto(sock, buffer, sizeof(unsigned char)*bufSize+8, 0, &sll, sizeof(sll)) < 0){  
            perror("sendto");  
            return 1;  
        }  
        printf("Sendto Success!\n");  

    }  
    free(buffer);
    close(sock );
    return 0;  
}  

wireshark抓取报文情况:

img

3.2 rawSocket接收文件后存储到指定路径

rawsocket_recvfile.c

#include "rawsocket.h"  

#define _PATH_PROCNET_DEV               "/proc/net/dev"  

static char *get_name(char *name, char *p)  
{  
    while (isspace(*p))  
            p++;  
  
    while (*p) {  
            if (isspace(*p))  
        break;  
            if (*p == ':') {    /* could be an alias */  
        char *dot = p, *dotname = name;  
        *name++ = *p++;  
        while (isdigit(*p))  
        *name++ = *p++;  
        if (*p != ':') {    /* it wasn't, backup */  
        p = dot;  
        name = dotname;  
        }  
        if (*p == '\0')  
        return NULL;  
        p++;  
        break;  
    }  
    *name++ = *p++;  
    }  
    *name++ = '\0';  
    return p;  
}  
  
/** 
 * read_netdev_proc - read net dev names form proc/net/dev 
 * @devname: where to store dev names, devname[num][len] 
 */  
static int read_netdev_proc(void *devname, const int num, const int len)  
{  
    FILE *fh;  
    char buf[512];  
        int cnt = 0;  
        char *dev = (char *)devname;  
  
        if(devname == NULL || num < 1 || len < 4){  
            printf("read_netdev_proc: para error\n");  
            return -1;  
        }  
  
        memset(devname, 0, len * num);  
  
    fh = fopen(_PATH_PROCNET_DEV, "r");  
    if (!fh) {  
        fprintf(stderr, "Warning: cannot open %s (%s). Limited output.\n",  
            _PATH_PROCNET_DEV, strerror(errno));   
        return -1;  
      }  
  
    fgets(buf, sizeof buf, fh); /* eat two line */  
    fgets(buf, sizeof buf, fh);  
  
        cnt = 0;  
    while (fgets(buf, sizeof buf, fh) && cnt < num) {  
            char *s, name[IFNAMSIZ];  
            s = get_name(name, buf);  
  
            strncpy(devname, name, len);  
            devname += len;  
            printf("get_name: %s\n", name);  
    }  
  
    if (ferror(fh)) {  
            perror(_PATH_PROCNET_DEV);  
    }  
  
    fclose(fh);  
    return 0;  
}  
  
/** 
 * get_hwaddr - get netdevice mac addr  
 * @name: device name, e.g: eth0 
 * @hwaddr: where to save mac, 6 byte hwaddr[6] 
 * @return: 0 on success, -1 on failure 
 */  
int get_hwaddr(char *name, unsigned char *hwaddr)  
{  
    struct ifreq ifr;  
    unsigned char memzero[6];  
    int sock;  
  
    if(name == NULL || hwaddr == NULL){  
        printf("get_hwaddr: NULL para\n");  
        return -1;  
    }  
  
 sock = socket(AF_INET, SOCK_STREAM, 0);  
    if(sock < 0){  
        printf("get_hwaddr: socket error\n");  
        //return -1;  
    }  
  
    //get eth1 mac addr  
    memset(hwaddr, 0, 6);  
    memset(&ifr, 0, sizeof(ifr));  
    strncpy(ifr.ifr_name, name, 6);  
    if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0){  
            perror("get_hwaddr ioctl:");  
            close(sock);  
            return -1;  
    } else {  
            memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, 6);  
            //printf("hwaddr: %2x : %2x : %2x : %2x : %2x : %2x\n", hwaddr[0], hwaddr[1],hwaddr[2], hwaddr[3],hwaddr[4], hwaddr[5]);  
    }  
  
    memset(memzero, 0, 6);  
    if(memcmp(memzero, hwaddr, 6) == 0){  
        printf("no mac\n");  
        return -1;  
    }  
  
    close(sock);  
    return 0;  
}  

void printhex(void *hex, int len, char *tag)  
{  
    int i;  
    unsigned char *p = (unsigned char *)hex;  
  
    if(len < 1)  
        return;  
  
    for(i = 0; i < len - 1; i++){  
        if(*p < 0x10)  
            printf("0%x%s", *p++, tag);  
        else  
            printf("%2x%s", *p++, tag);  
    }  
  
    if(*p < 0x10)  
        printf("0%x\n", *p++);  
    else  
        printf("%2x\n", *p++);  
}  




int main()  
{  
    int i;  
    unsigned char hwaddr[6];  
    char devname[3][7];  
    unsigned char buf[1024]; // for revevied packet  
    const char *fileName = "abc.bin";
    int ret = 0;

    read_netdev_proc(devname, 3, 7);  
  
    for(i = 0; i < 3 && get_hwaddr(devname[i], hwaddr) != 0; i++){   
        //empty  
    }  
  
    printf("devname: [ %s ]\t", devname[i]);  
    printhex(hwaddr, 6, ":");  

    int sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));  
    if(sock < 0){  
        perror("sock");  
        return -1;  
    }


#if 1
    unsigned char packet_type[] = {0x08,0x06};
    int nCount;
    while(1){  

        memset(buf,0,1024);

        while((nCount = recvfrom(sock,buf,1024,0,NULL,NULL)) > 0)
        {
            printf("nCount:%d\n",nCount);
            if(0 == memcmp(packet_type,&buf[12],2))
            {
                FILE* write = fopen(fileName,"a+");
                if(!write)
                {
                    perror("file write failed:\n");
                    return -1;
                }

                printf("same recv: ");  
                printhex(&buf[14], nCount-12, " ");  
		// len要-12去6个字节的srcmac和6个字节的dstmac
                ret += fwrite(&buf[14],nCount-12,1,write);

                //  printf("receive file success!\n");
                fclose(write);
            }
        }

    }  
#else  
    while(1){  
        ret = recvfrom(sock, buf, 1024, 0, NULL, NULL);  
        printf("recv: ");  
        printhex(buf, ret, " ");  
    }  
#endif  
    close(sock );
    return 0;  
}  


接收存储文件的内容:

img

参考文章:

读取linux下的网络设备的mac地址与发送原始数据包_linux检查报文源mac-CSDN博客

UDP协议 sendto 和 recvfrom 浅析与示例 - 阳光长脸兽 - 博客园 (cnblogs.com

(十三)Packet socket 和 sockaddr_ll - xtusir - 博客园 (cnblogs.com)

posted @ 2024-07-24 10:54  Emma1111  阅读(195)  评论(0编辑  收藏  举报