Skip to content

Commit

Permalink
Don't stop reading from socket after 4096 bytes
Browse files Browse the repository at this point in the history
Closes #45
  • Loading branch information
exhuma committed Jul 4, 2018
1 parent 22494e6 commit 3206f6b
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion puresnmp/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,34 @@
RETRIES = 3


def recv_all(sock):
'''
Read data from socket using ``sock.recv`` until no bytes are left to read.
Unfortunately, decoding the byte-length is non-trivial according to the
X690 standard (see :py:func:`puresnmp.x690.types.pop_tlv` and
:py:func:`puresnmp.x690.util.decode_length` for more details.
This means a simple call to ``recv`` does not have length-information and
detecting the end of the stream is more error-prone.
This could be refactored in the future to meld the x690 and "transport"
layers together.
See https://stackoverflow.com/a/17697651/160665
'''
buffer_size = 4096 # 4 KiB
chunks = []
while True:
chunk = sock.recv(buffer_size)
chunks.append(chunk)
if len(chunk) < buffer_size:
# either 0 or end of data
break
data = b''.join(chunks)
return data


def send(ip, port, packet, timeout=2): # pragma: no cover
# type: ( str, int, bytes, int ) -> bytes
"""
Expand All @@ -47,7 +75,7 @@ def send(ip, port, packet, timeout=2): # pragma: no cover
LOG.debug('Sending packet to %s:%s (attempt %d/%d)\n%s',
ip, port, (num_retry+1), RETRIES, hexdump)
sock.sendto(packet, (ip, port))
response = sock.recv(8192)
response = recv_all(sock)
break
except socket.timeout:
LOG.debug('Timeout during attempt #%d',
Expand Down

0 comments on commit 3206f6b

Please sign in to comment.