aboutsummaryrefslogtreecommitdiff
path: root/protocol.c
blob: d3502216ae36cd124e1b94b5030bcf8c1ac6b008 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <sys/types.h>
#include <sys/socket.h>

#include "protocol.h"

#define TIMEOUT 100000 // 100ms in microseconds

int send_all(int sock, char *buf, int *len)
{
    struct timeval timeout;      
    timeout.tv_sec = 0;
    timeout.tv_usec = 100000;
    // if (setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, &timeout,
    //             sizeof timeout) < 0)
    //     perror("setsockopt failed\n");

    int total = 0;        // how many bytes we've sent
    int bytesleft = *len; // how many we have left to send
    int n;

    while(total < *len) {
        n = send(sock, buf+total, bytesleft, 0);
        if (n == -1) { break; }
        total += n;
        bytesleft -= n;
    }

    *len = total; // return number actually sent here

    return n==-1?-1:0; // return -1 on failure, 0 on success
} 

int recv_all(int sock, char *buf, int *len)
{
    // setup the timeout on the socket
    struct timeval timeout;      
    timeout.tv_sec = 0;
    timeout.tv_usec = TIMEOUT;
    if (setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, &timeout,
                sizeof timeout) < 0)
        perror("setsockopt failed\n");

    // printf("start: %ld\n", start);
    int total = 0;        // how many bytes we've sent
    int bytesleft = *len; // how many we have left to send
    int n;

    while(total < *len) {
        n = recv(sock, buf+total, bytesleft, 0);
        // start = time(NULL);
        if (n == -1) { break; }
        total += n;
        bytesleft -= n;
    }

    timeout.tv_sec = 0;
    timeout.tv_usec = 0;
    if (setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, &timeout,
                sizeof timeout) < 0)
        perror("setsockopt failed\n");


    *len = total; // return number actually sent here

    return n==-1?-1:0; // return -1 on failure, 0 on success
}