Home > Software engineering >  Can a minimum number of bytes be set for python's socket.recvfrom()?
Can a minimum number of bytes be set for python's socket.recvfrom()?

Time:12-04

There are 2 types of packets Im sending from my server and trying to analyze:

  • context packets of length 27 words (108 bytes)

  • data packets of length 250 words (1000 bytes)

I'm using python's socket recvfrom() method but documentation about this seems to be scarce.. Currently I have the following code snippet:

import socket


rx_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rx_socket.bind(("", 50000))

packets = []
for _ in range(10):
    data, _ = rx_socket.recvfrom(8192)
    packets.append(data)

My problem is that for each packet that ends up in packets list is a context packet. I know this because the length of each element is 27. I need to be able to receive the data packets, is there a way to specify a minimum number of bytes before recvfrom() returns? Thank you for any help!

CodePudding user response:

is there a way to specify a minimum number of bytes before recvfrom() returns?

No. One can only specify the maximum amounts of bytes to read.

Note though that with datagrams (i.e. UDP) each recv will return exactly one datagram and send will send everything given in exactly one datagram, which also implies there is a 1:1 relationship between send on one side and recv on the other side.

Also it is not possible to pick datagrams based on there size and let the system ignore the others. Everything is delivered to the socket buffer (as long as there is room) in the order received. The only way to get to the larger datagrams is to explicitly remove every datagram received before by calling recv.

CodePudding user response:

My problem is that for each packet that ends up in packets list is a context packet. I know this because the length of each element is 27.

Well, you are reading only 10 packets and then stopping. Is it possible that the data packets arrive after packet 10?

I need to be able to receive the data packets

The recvfrom() call you already have will work perfectly fine for that purpose. You are telling recvfrom() to read the next datagram, using a 8K buffer. Your data packets are well within that size.

If anything, the only thing you need to change is your loop condition, such as by using while True instead of for _ in range(10).

If you are not receiving any data packets, that means either you are stopping your reading before they arrive, or they are simply not being sent to your listening port to begin with. Use a packet sniffer, like Wireshark, to verify that.

is there a way to specify a minimum number of bytes before recvfrom() returns?

No, there is not. Each call to recvfrom() will dequeue and return the next datagram on the socket, regardless of its size. However, if the datagram is larger than the buffer size you specify, the datagram will be truncated.

  • Related