我尝试使用原始套接字编程来捕获所有到达我的NIC的UDP数据包。但是,我遇到了一个奇怪的问题。当我的程序在运行时,我的套接字描述符会自动更改。以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <netinet/tcp.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <arpa/inet.h>
int main () {
int sockfd = socket (PF_INET, SOCK_RAW, IPPROTO_UDP);
if (sockfd < 0) {
perror ("socket failed");
return -1;
}
char *buf = malloc (8192);
memset (buf, 0, 8192);
if (!buf) {
perror ("calloc failed\n");
return -1;
}
int ret_recv;
i:
while ((ret_recv = recv (sockfd, buf, 8192, 0)) > -1) {
printf ("%d\n", ret_recv);
struct iphdr *iph = (struct iphdr *) buf;
//struct udphdr *udph = (struct udphdr *) (buf + sizeof (struct iphdr));
struct tcphdr *tcph = (struct tcphdr *) (buf + sizeof (struct iphdr));
char ip[4];
printf ("source ip: %s\n", inet_ntop (AF_INET, &iph->saddr, ip, sizeof (struct sockaddr_in)));
printf ("dest ip: %s\n", inet_ntop (AF_INET, &iph->daddr, ip, sizeof (struct sockaddr_in)));
//printf ("port: %d\n", ntohs (udph->source));
printf ("port: %d\n", ntohs (tcph->source));
}
perror ("recv failed");
//goto i;
return 0;
}
在我的输出结果中,没有无限循环打印数据包信息,只有一个数据包信息被打印。因此我使用gdb进行了检查。我使用了
display sockfd
指令。在socket调用后,sockfd的值为7。然后在while循环中,在执行dest ip的printf之后,sockfd的值更改为808988216。因此,recv函数失败并报错“坏的文件描述符”。我找不到实际出了什么问题。感谢您的帮助。 :-)
malloc()
之后才检查其结果?当你调用malloc()
而不是calloc()
时,为什么要打印“calloc失败”?当调用calloc()
可以同时完成两者并使您的调试输出正确时,为什么要调用malloc()
和memset()
?为什么要使用struct tcphdr *
来查看UDP数据包? - user207421