原始套接字指定网口发包

13 篇文章 0 订阅
2 篇文章 0 订阅
#include <stdio.h>   
#include <stdlib.h> 
#include <string.h>    
#include <netinet/in.h>  
#include <sys/socket.h>   
#include <netinet/ether.h>
#include <netpacket/packet.h> 
#include <net/if.h> 
#include <sys/ioctl.h>
#include <unistd.h>
#include <arpa/inet.h>    

int main()
{
	unsigned char buf[1024] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
							 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
	unsigned int buf_len = 16;
	struct sockaddr_ll sll;
	struct ifreq ethreq;
	int sock_raw_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	
	if(sock_raw_fd < 0)
	{
		perror("socket");
		return -1;
	}

	strncpy(ethreq.ifr_name, "eth2", IFNAMSIZ);         //指定网卡名称    
	if(-1 == ioctl(sock_raw_fd, SIOCGIFINDEX, ereq))    //获取网络接口    
	{    
	    perror("ioctl");    
	    close(sock_raw_fd);    
	    exit(-1);    
	}    
	/*将网络接口赋值给原始套接字地址结构*/    
	bzero(&sll, sizeof(sll));    
	sll.sll_ifindex = ethreq.ifr_ifindex;    

	int len = sendto(sock_raw_fd, buf, buf_len, 0 , (struct sockaddr *)&sll, sizeof(sll));    
	if(len == -1)    
	{    
	    perror("sendto");    
	}   
	return 0;
}
	

参考链接:https://blog.csdn.net/m0_67401660/article/details/124294613

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值