原始套接字 udp 接收
时间: 2024-11-15 14:28:36 浏览: 47
原始套接字可以接收和发送内核没有处理的数据包,因此可以用于接收和发送任何协议类型的数据包,包括UDP协议。下面是使用原始套接字接收UDP数据包的步骤:
1. 使用socket函数创建原始套接字,指定通信域为AF_PACKET,套接字类型为SOCK_RAW,协议类型为ETH_P_ALL。
2. 使用recvfrom函数接收数据包,指定套接字文件描述符、接收缓冲区、缓冲区大小、标志位和源地址结构体。
3. 解析接收到的数据包,获取UDP头和数据部分。
4. 关闭套接字。
示例代码如下:
```
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#define BUF_SIZE 65536
int main(int argc, char const *argv[]) {
int sockfd, n;
char buffer[BUF_SIZE];
struct sockaddr_in source_addr;
socklen_t addr_len = sizeof(source_addr);
// 创建原始套接字
if ((sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1) {
perror("fail to create socket");
exit(1);
}
// 接收数据包
while ((n = recvfrom(sockfd, buffer, BUF_SIZE, 0, (struct sockaddr *)&source_addr, &addr_len)) > 0) {
// 解析UDP头和数据部分
struct udphdr *udp_header = (struct udphdr *)(buffer + sizeof(struct iphdr));
char *data = buffer + sizeof(struct iphdr) + sizeof(struct udphdr);
// 打印UDP数据
printf("UDP data: %s\n", data);
}
// 关闭套接字
close(sockfd);
return 0;
}
```
阅读全文
相关推荐


















