如何在LINUX中过滤RAW套接字中的数据包

RAW Socket:如何过滤RAW Socket数据包? 我试图捕获服务器程序中的UDP packets ,但它收到所有的数据包。 有什么function或命令来过滤在Linux的数据包。

  #include <sys/socket.h> #include <netinet/in.h> raw_socket = socket(AF_INET, SOCK_RAW, int protocol); 

使用这个协议字段我们可以捕获特定的数据包

 int fd = socket (PF_INET, SOCK_RAW, IPPROTO_TCP); char buffer[8192]; /* single packets are usually not bigger than 8192 bytes */ while (read (fd, buffer, 8192) > 0) { printf ("Caught tcp packet: %s\n", buffer+sizeof(struct iphdr)+sizeof(struct tcphdr)); } 

上面的代码将捕获所有的TCP数据包。 对于UDP我们也可以使用

socket (PF_INET, SOCK_RAW, IPPROTO_UDP);