Completed
Push — master ( 18d750...3bad9e )
by Andrii
11:56
created

read()   A

Complexity

Conditions 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 3
c 4
b 0
f 0
dl 0
loc 8
rs 9.4285
1
import struct
2
3
# http://www.bortzmeyer.org/4934.html
4
def format_32():
5
    # Get the size of C integers. We need 32 bits unsigned.
6
    format_32 = ">I"
7
    if struct.calcsize(format_32) < 4:
8
        format_32 = ">L"
9
        if struct.calcsize(format_32) != 4:
10
            raise Exception("Cannot find a 32 bits integer")
11
    elif struct.calcsize(format_32) > 4:
12
        format_32 = ">H"
13
        if struct.calcsize(format_32) != 4:
14
            raise Exception("Cannot find a 32 bits integer")
15
    else:
16
        pass
17
    return format_32
18
19
FORMAT_32 = format_32()
20
21
def int_from_net(data):
22
    return struct.unpack(FORMAT_32, data)[0]
23
24
def int_to_net(value):
25
    return struct.pack(FORMAT_32, value)
26
27
def write(socket, data):
28
    # +4 for the length field itself (section 4 mandates that)
29
    # +2 for the CRLF at the end
30
    length = int_to_net(len(data) + 4 + 2)
31
    socket.send(length)
32
    return socket.send(data + "\r\n")
33
34
def read(socket):
35
    net = socket.recv(4)
36
    if net:
37
        length = int_from_net(net)-4
38
        buffer = ''
39
        while (length>len(buffer)):
40
            buffer += socket.recv(4096)
41
        return buffer
42
43