RAW Socket:如何过滤RAW Socket
数据包? 我试图捕获服务器程序中的UDP packets
,但它收到所有的数据包。 有什么function或命令来过滤在Linux的数据包。
使用LSF / BPF(见https://www.kernel.org/doc/Documentation/networking/filter.txt http://www.freebsd.org/cgi/man.cgi?query=bpf&sektion=4 )或一个更高层次的接口pcap
#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);