HW12/socket_wrapper.c
2020-12-04 07:48:03 +00:00

91 lines
2.4 KiB
C

#include <signal.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <poll.h>
#include <netdb.h>
#include <string.h>
#include "socket_wrapper.h"
int getBufferSizeFrom(int sock){
int buffer_sz;
socklen_t len = sizeof(buffer_sz);
//getsockopt is thread-safe
if(getsockopt(sock,SOL_SOCKET,SO_SNDBUF,&buffer_sz,&len) < 0){
perror("failed to get sock buffer size: getsockopt");
buffer_sz = DEFAULT_BUF_SIZE;/*set to default*/
}
if(buffer_sz < MINIMUM_BUF_SIZE)
buffer_sz = MINIMUM_BUF_SIZE;
return buffer_sz;
}
ssize_t timeout_recv(int fd,void * buf,size_t n,int timeout)
{
ssize_t ret;
int poll_ret;
struct pollfd fd_single;
fd_single.fd = fd;
fd_single.events = POLL_IN;
poll_ret = (poll(&fd_single,1,timeout * 1000));
if (poll_ret < 0) return -1;
else if(poll_ret == 0) return -2;
switch (fd_single.revents){
case POLLHUP: //We'll treat hangups state like timeouts state.
return -2;
case POLLERR:
case POLLNVAL:
return -1;
case POLL_IN:
ret = recv(fd,buf,n,0);
assert(ret != 0);
return ret;
default:
assert(0 && "unreachable");
}
assert(0 && "unreachable");
}
ssize_t recv_until_byte(int fd,void * buf, size_t n,int timeout){
ssize_t cur = 0;
uint8_t * b = buf;
while (cur < n)
{
ssize_t r = timeout_recv(fd,&b[cur],n-cur,timeout);
if (r < 0){
return r;
}
cur += r;
}
assert(cur == n);
return cur;
}
int getsockaddrbyname(int domain,int type, int protocol, const char * hostname_str, struct sockaddr * retaddr){
struct addrinfo hints;
struct addrinfo * result, *entry;
int ret, i;
memset(&hints,0,sizeof(hints));
hints.ai_family = domain;
hints.ai_socktype = type;
hints.ai_flags = 0;
hints.ai_protocol = protocol;
//try 5 times
for (i = 0; i < 5; i++)
{
ret = getaddrinfo(hostname_str,NULL,&hints,&result);
if(ret == EAI_AGAIN) continue;
else if (ret != 0) return ret;
break;
}
if (ret != 0) return ret; //maybe name server doesn't work properly.
for (entry = result; entry != NULL; entry = entry->ai_next){
memcpy(retaddr,entry->ai_addr,sizeof(*retaddr));
}
freeaddrinfo(result);
return ret;
}