将recvfrom()与原始套接字一起使用:一般的疑问 [英] Using recvfrom() with raw sockets : general doubt

查看:338
本文介绍了将recvfrom()与原始套接字一起使用:一般的疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个原始套接字,该套接字从数据链路层获取所有IPv4数据包(数据链路层标头已删除).对于读取数据包,我使用recvfrom.

I have created a raw socket which takes all IPv4 packets from data link layer (with data link layer header removed). And for reading the packets I use recvfrom.

我的疑问是: 假设由于操作系统进行了一些调度,我的进程处于睡眠状态1秒钟.唤醒后,它在此原始套接字上执行了recvfrom(要接收的字节数为1000)(目的是仅接收一个 IPv4数据包,并说该数据包的大小为380个字节).并假设许多网络应用程序在此期间也同时运行,因此所有IPv4数据包必须已在此套接字的接收缓冲区中排队.因此,现在recvfrom将返回所有1000字节(以及从第381个字节开始的其他IPv4数据包),因为它在缓冲区中有足够的数据可以返回.尽管我的程序只打算了解一个IPv4数据包

My doubt is: Suppose due to some scheduling done by OS, my process was asleep for 1 sec. When it woke up,it did recvfrom (with number of bytes to be received say 1000) on this raw socket (with the intention of receiving only one IPv4 packet and say the size of this packet is 380 bytes). And suppose many network applications were also running simultaneously during this time, so all IPv4 packets must have been queued in the receive buffer of this socket. So now recvfrom will return all 1000 bytes (with other IPv4 packets from 381th byte onwards) bcoz it has enough data in its buffer to return. Although my program was meant to understand only one IPv4 packet

那么该如何预防呢?我应该逐字节读取并解析每个字节,但是效率很低.

So how to prevent this thing? Should I read byte by byte and parse each byte but it is very inefficient.

推荐答案

IIRC,即使队列中有更多数据,recvfrom()一次只会返回一个数据包.

IIRC, recvfrom() will only return one packet at a time, even if there are more in the queue.

这篇关于将recvfrom()与原始套接字一起使用:一般的疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆