链路层原始套接字编程-客户端

44 篇文章 0 订阅
17 篇文章 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>


#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=10, nsend=0;
        char    buf[LEN];
        struct sockaddr_ll      sa;
        struct ifreq    ifr;
        char    if_name[]="eth0";
        char    dst_mac[6]={0x00,0x50,0xC2,0x25,0x8A,0x20};
        char    src_mac[6];
        short   type = htons(0x8902);

        memset(&sa, 0, sizeof(struct sockaddr_ll));
        memset(buf, 0, sizeof(buf));

        //create socket
        fd = socket(PF_PACKET, SOCK_RAW, htons(0x8902));
        if(fd < 0){
                printf("socket error, %d\n", errno);
                return errno;
        }

        //get index
        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(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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值