From fcc0658730e541477fa60995d8bd82ff87163b92 Mon Sep 17 00:00:00 2001 From: tomsmeding Date: Thu, 19 Jan 2017 18:30:07 +0100 Subject: Separate sock_/tcp_ like regexbattle --- tcp.c | 191 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 191 insertions(+) create mode 100644 tcp.c (limited to 'tcp.c') diff --git a/tcp.c b/tcp.c new file mode 100644 index 0000000..65da79d --- /dev/null +++ b/tcp.c @@ -0,0 +1,191 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include "global.h" +#include "memory.h" +#include "tcp.h" + +i64 tcp_read_line(int sock,char **buf,i64 *bufsz){ + if(*bufsz==0||*buf==NULL){ + *bufsz=512; + *buf=malloc(*bufsz,char); + } + i64 len=0; + while(true){ + if(len==*bufsz-1){ + *bufsz*=2; + *buf=realloc(*buf,*bufsz,char); + } + i64 ret=recv(sock,*buf+len,1,0); + if(ret<=0)return -1; + if((*buf)[len]=='\n'){ + (*buf)[len]='\0'; + return len; + } + len++; + } +} + +i64 tcp_read_data(int sock,char *buf,i64 length){ + i64 got=0; + while(gotnitems=nitems; + list->items=malloc(nitems,char*); + walker=argstart; + for(i64 i=0;iitems[i]=strdup(strsep(&walker," ")); + } + + return list; +} + +void tcp_list_destroy(TcpList *list){ + free(list->items); + free(list); +} + + +static const char* itoa(int n){ + static char buf[64]; + sprintf(buf,"%d",n); + return buf; +} + + +int tcp_connect(const char *hostname,int port){ + struct addrinfo hints,*res; + memset(&hints,0,sizeof(hints)); + hints.ai_family=AF_UNSPEC; + hints.ai_socktype=SOCK_STREAM; + int ret=getaddrinfo(hostname,itoa(port),&hints,&res); + if(ret!=0){ + return -1; + } + + int sock=socket(res->ai_family,res->ai_socktype,res->ai_protocol); + if(sock==-1)return -1; + if(connect(sock,res->ai_addr,res->ai_addrlen)==-1)return -1; + return sock; +} -- cgit v1.2.3-70-g09d2