How to filter Packets in RAW socket in LINUX

こ雲淡風輕ζ 提交于 2019-12-12 23:24:51

问题


RAW Socket: How to filter packets in RAW Socket ? I was trying to capture UDP packets in a server Program but its receiving all the packets. Is there any function or command to filter the packets in linux.


回答1:


Use LSF/BPF (see https://www.kernel.org/doc/Documentation/networking/filter.txt an http://www.freebsd.org/cgi/man.cgi?query=bpf&sektion=4) or for a higher-level interface, pcap




回答2:


 #include <sys/socket.h>
 #include <netinet/in.h>

 raw_socket = socket(AF_INET, SOCK_RAW, int protocol);

Using this protocol Field we can capture particular packet.

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));
}

above code will capture all TCP packets. Similarly for UDP we can use

socket (PF_INET, SOCK_RAW, IPPROTO_UDP);



来源:https://stackoverflow.com/questions/18852486/how-to-filter-packets-in-raw-socket-in-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!