编一个使用原始套接字收网络数据的代码
时间: 2024-12-02 17:22:21 浏览: 6
使用原始套接字接收网络数据通常涉及以下几个步骤,在这里我们假设你已经创建了一个原始套接字并设置了相关的参数。这是一个简单的例子,演示了如何在Linux下使用C语言通过原始套接字读取网络数据(例如从UDP套接字接收):
```c
#include <sys/socket.h>
#include <linux/if.h>
#include <linux/if_packet.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#define BUF_SIZE 2048
int main() {
int sock, index;
struct sockaddr_ll addr;
char buffer[BUF_SIZE];
// 获取网卡索引
sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_IP)); // ETH_P_IP 或者 ETH_P_UDP
if (sock < 0) {
perror("Socket creation failed");
return -1;
}
if (ioctl(sock, SIOCGIFINDEX, &ifr) < 0) {
perror("Getting interface index failed");
close(sock);
return -1;
}
index = ifr.ifr_ifindex;
// 监听特定网卡
memset(&addr, 0, sizeof(addr));
addr.sll_family = AF_PACKET;
addr.sll_protocol = htons(ETH_P_UDP); // 如果你想监听UDP数据
addr.sll_index = index;
// 接收数据
socklen_t len = sizeof(addr);
while (true) {
ssize_t bytes_received = recvfrom(sock, buffer, BUF_SIZE, 0, (struct sockaddr*)&addr, &len);
if (bytes_received <= 0) {
perror("Receiving data failed");
break;
}
// 检查是否收到完整的UDP包
struct udphdr *udph = (struct udphdr *) (buffer + sizeof(struct iphdr));
if (bytes_received >= sizeof(struct iphdr) + sizeof(*udph)) {
uint16_t src_port = ntohs(udph->source);
uint16_t dst_port = ntohs(udph->dest);
char* payload = buffer + sizeof(struct iphdr) + sizeof(*udph);
printf("Received UDP packet from %d:%d: %.*s\n", src_port, dst_port, bytes_received - sizeof(*udph), payload);
} else {
printf("Incomplete UDP packet received.\n");
}
}
close(sock);
return 0;
}
```
这个程序会不断接收并打印来自指定端口的UDP数据。请注意,原始套接字的操作可能会受到权限限制,确保你有正确的权限访问网络设备。
阅读全文