在 Python 中读取 UDP 数据包的缓冲区大小

2022-01-22 00:00:00 python sockets udp

问题描述

我正在尝试找出/调整网络缓冲区的大小:

导入套接字袜子 = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)sock.getsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF)212992

这到底是什么?~ 0.2 MB ..!?

但是,如果我在其他地方(即在命令行上)寻找缓冲区大小:

sampsa@sampsa-xps13:~/python/sockets$ cat/proc/sys/net/ipv4/tcp_wmem4096 16384 4194304

.. 我得到 4096 个字节.

让我们尝试设置缓冲区大小,然后检查它的值:

sock.setsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF,1024)sock.getsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF)2304

发生了什么事?

将 SOL_SOCKET 替换为 SOL_UDP 会给出协议不可用"

如何调整最大值.UDP数据包的大小..甚至找出来?

解决方案

我想说,如何找出/调整缓冲区的大小

您使用 SO_RCVBUF 的方式是正确的.但请注意,根据您的设置和操作系统,您使用 getsockopt 返回的值可能与使用 setsockopt 设置的值不同.在 Linux socket(7) 状态下:

SO_RCVBUF设置或获取最大套接字接收缓冲区(以字节为单位).内核加倍此值(为簿记开销留出空间)时使用setsockopt(2),这个加倍的值由 getsockopt(2) 返回.默认值由/proc/sys/net/core/rmem_default 文件设置,并且最大允许值由/proc/sys/net/core/rmem_max 文件设置.此选项的最小(加倍)值为 256.

<块引用>

顺便说一句,网络套接字是 FIFO 吗?first in - 当缓冲区饱和时首先丢弃?

据我所知,如果缓冲区已满,接收将失败.它不会丢弃已接收但未处理的数据以为新数据腾出空间.

I am trying to find out / adjust the size of network buffers:

import socket

sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

sock.getsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF)
212992

What on earth is this? ~ 0.2 MBytes ..!?

However, if I am looking for the buffer size elsewhere, i.e. on the command line:

sampsa@sampsa-xps13:~/python/sockets$ cat /proc/sys/net/ipv4/tcp_wmem
4096    16384   4194304

.. I get 4096 bytes.

Let's try to set the buffer size and then check its value:

sock.setsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF,1024)

sock.getsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF)     
2304

What's going on?

Substituting SOL_SOCKET with SOL_UDP gives "Protocol not available"

How can I adjust the max. size of the UDP packet .. or even find it out?

解决方案

I wanted to say, how to find out / adjust the size of the buffer

The way you did with SO_RCVBUF was correct. But note that depending on your setting and on your OS you might get different values back with getsockopt than you set with setsockopt. On Linux socket(7) states:

SO_RCVBUF
Sets or gets the maximum socket receive buffer in bytes.  The kernel doubles
this value (to allow space for bookkeeping overhead) when it is set using 
setsockopt(2), and this doubled  value  is  returned  by  getsockopt(2). 
The default value is set by the /proc/sys/net/core/rmem_default file, and
the maximum allowed value is set by the /proc/sys/net/core/rmem_max file.  
The minimum (doubled) value for this option is 256.

And, btw, are the network sockets FIFO ? first in - first discarded when the buffer gets saturated?

As far as I know if the buffer is full receiving will fail. It will not discard already received but not processed data to make room for new data.

相关文章