也许我误解了你的问题(例如,我不能完全理解“不想要原始数据包只是 TCP 有效负载”),但是一个简单的原始套接字(IPPROTO_TCP)连接然后用 recv() 嗅探就可以了工作。您在 recv() 中将最大缓冲区大小指定为参数,但是当 TCP 负载到来时,它将被报告回来 - 无需等待缓冲区填满。下面是一些打印 TCP 数据包的代码摘录:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include // your header to print out bytes and error messages here
int main(void) {
int i, recv_length, sockfd;
u_char buffer[9000];
if ((sockfd = socket(PF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)
// your error message here
for(i=0; i < 3; i++) {
recv_length = recv(sockfd, buffer, 8000, 0);
printf("Got a %d byte packet\n", recv_length);
// your routine to print out bytes here
}
}
如果这不是您所关心的,请澄清。
编辑:根据我所听到和阅读的内容,使用库 pcap (libcap) 优于使用原始套接字(更可靠;非常强大 - 由编写 tcpdump 的人编写)。但是,我自己仍在学习 pcap,到目前为止,我一直在努力让它在无线设备上正常工作。但是,如果您持续需要这个,也可以考虑一下。