原始套接字SOCK_RAW发送UDP数据包

本文介绍如何利用原始套接字在C语言中创建和发送UDP数据包,包括头文件head.h和实现代码raw_udp.c的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      使用原始套接字发送udp数据包,从传输层封包到链路层(mac头+ip头+udp头)。udp数据包,从传输层封包到链路层(mac头+ip头+udp头)。
 
 

head.h文件如下:

 

#ifndef _HEAD_H
#define _HEAD_H    

#define BUFFER_MAX 2048
#define PCKT_LEN 8492

#pragma pack (1)
//ethernet head 14 bytes
struct ether
{
	char dmac[6];
	char smac[6];
	char eth_typ_len[2];
};


//ip head 20 bytes
struct ipheader {

 unsigned char      iplv;//iph_ihl:5, iph_ver:4;

 unsigned char      iph_tos;

 unsigned short int iph_len;

 unsigned short int iph_ident;

// unsigned uint8_t      iph_flag;

 unsigned short int iph_offset;//16bit include flag and offset

 unsigned char      iph_ttl;

 unsigned char      iph_protocol;

 unsigned short int iph_chksum;

 unsigned int       iph_sourceip;

 unsigned int       iph_destip;

};

//udp head 8 bytes
struct udpheader {

 unsigned short int udph_srcport;

 unsigned short int udph_destport;

 unsigned short int udph_len;

 unsigned short int udph_chksum;

};

//tcp head 20bytes
struct tcphdr
{
    unsigned short int source;  
    unsigned short int dest;   
    unsigned int seq;  
    unsigned int ack_seq; 
    unsigned short int tcp_len;
#if 0
    unsigned short int doff:4;
    unsigned short int res1:4;
    unsigned short int res2:2;
    unsigned short int urg:1;
    unsigned short int ack:1;
    unsigned short int psh:1;
    unsigned short int rst:1;
    unsigned short int syn:1;
    unsigned short int fin:1;
#endif
    unsigned short int window;  
    unsigned short int check;  
    unsigned short int urg_prt;  
};

#pragma pack ()

#endif

 

 

 

 

 

 
 

raw_udp.c文件如下:

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值