使用原始套接字捕获传入和传出的数据包(capturing both incoming and outgoing packets using raw socket)

系统教程 行业动态 更新时间:2024-06-14 17:01:31
使用原始套接字捕获传入和传出的数据包(capturing both incoming and outgoing packets using raw socket)

我正在用C编写一个工具,用于记录在我的Linux系统上运行的不同应用程序的数据使用情况。 为此,我创建了一个原始套接字然后用“eth0”绑定它,这是我的接口的名称。 但我的问题是,这个套接字只捕获传入的数据包(即:目的MAC地址作为我系统的MAC地址的数据包)。 我找不到任何源MAC地址作为我系统的MAC地址的数据包。 所以它意味着我自己的机器写的数据包不会被原始套接字捕获。 但我想在两个方向捕获数据包,以识别上传和下载的数据大小。 有人可以帮忙吗?

int main() { int rs,len; struct sockaddr_ll addr; char buf[65535]; rs = socket(PF_PACKET,SOCK_RAW,htons(ETH_ALL)); setsockopt(rs,SOL_SOCKET,SO_BINDDEVICE,"eth0",4); while(recvfrom(rs,buf,65535,&addr,&len) > 0){ //print packets } return 0; }

I am writing a tool in C for logging data usage of different applications running on my Linux system. For this i had created a raw socket and then I bind it with "eth0" which is the name of my interface. But my problem is that, this sockets captures only incoming packets (ie: packets with destination MAC address as my system's MAC address). I can't find any packets that has source MAC address as my system's MAC address. So it means packets written by my own machine are not captured by the raw socket. But i want to capture packets in both directions for identifying uploaded and downloaded data size. Can anybody help?

int main() { int rs,len; struct sockaddr_ll addr; char buf[65535]; rs = socket(PF_PACKET,SOCK_RAW,htons(ETH_ALL)); setsockopt(rs,SOL_SOCKET,SO_BINDDEVICE,"eth0",4); while(recvfrom(rs,buf,65535,&addr,&len) > 0){ //print packets } return 0; }

最满意答案

我在搜索你的问题时找到了这个。 我没试过这个。 可能这会起作用。

int v=0; v = PACKET_MASK_ANY & ~(1<<PACKET_OUTGOING) & ~(1 << PACKET_LOOPBACK); setsockopt( raw_sock, SOL_PACKET, PACKET_RECV_TYPE, &v, sizeof(v));

I have found this while searching over your problem. I haven't tried this. May be this will work.

int v=0; v = PACKET_MASK_ANY & ~(1<<PACKET_OUTGOING) & ~(1 << PACKET_LOOPBACK); setsockopt( raw_sock, SOL_PACKET, PACKET_RECV_TYPE, &v, sizeof(v));

更多推荐

本文发布于:2023-04-20 16:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/eca26759a2378d56c2c0216adc7a2109.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据包   原始   capturing   incoming   socket

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!