#include #include #include "protocol.h" #define TCP_TIMEOUT 100000 // 100ms in microseconds int send_all(int sock, char *buf, int *len) { struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = TCP_TIMEOUT; // 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 = TCP_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 } int apply_timeout(int fd) { // handle handshake struct timeval tv; tv.tv_sec = 0; tv.tv_usec = TCP_TIMEOUT; if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) { perror("setsockopt (in apply_timeout)"); return -1; } return 1; } int remove_timeout(int fd) { // handle handshake struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) { perror("setsockopt (in remove_timeout)"); return -1; } return 1; }