diff --git a/lib.c b/lib.c index b216e5f..2566189 100644 --- a/lib.c +++ b/lib.c @@ -25,14 +25,14 @@ int xbind(const int port){ /* [0] Initialization =========================================================*/ - int xsocket, bound; + int xsocket, bound, clientsock; static struct sockaddr_in addr; /* [1] Create xsocket =========================================================*/ /* (1) Create UPD xsocket */ - xsocket = socket(AF_INET, SOCK_DGRAM, 0); + xsocket = socket(AF_INET, SOCK_STREAM, 0); DEBUG&& debug("xbind", "creating server socket"); /* (r2-) Manage error */ @@ -68,9 +68,21 @@ int xbind(const int port){ } DEBUG&& printf("done\n"); + + + /* [4] Mark socket so it will listen for incoming co. + =========================================================*/ + DEBUG&& debug("xbind", "make socket listen for co"); + if( listen(xsocket, 1) < 0 ){ + DEBUG&& printf("error\n"); + return -1; + } + + DEBUG&& printf("done\n"); + - /* [4] Return xsocket + /* [5] Return xsocket =========================================================*/ return xsocket; } @@ -80,6 +92,56 @@ int xbind(const int port){ +int xlisten(const int xsocket, struct sockaddr_in* client, char* buffer, int bufsize){ + + /* [1] Initialization + =========================================================*/ + unsigned int sock_len; + int clientsock, bytes; + char buf[bufsize] = {'\0'}; + + + /* [2] Wait for client + =========================================================*/ + clientsock = accept(xsocket, (struct sockaddr*) client, &sock_len); + DEBUG&& debug("xlisten", "listening for client"); + + if( clientsock == -1 ){ + DEBUG&& printf("error\n"); + return -1; + } + + DEBUG&& printf("done\n"); + + + /* [3] Receive client data + =========================================================*/ + // while there is chunks to read + do{ + + /* (1) Receive buffer */ + bytes = recv(clientsock, buf, bufsize); + + /* (2) Copy to target */ + buffer = realloc(buffer, (strlen(buffer)+strlen(buf)) * sizeof(char ); + strcat(buffer, buf); + + }while( bytes > 0 ); + + + + + + + +} + + + + + + + int xconnect(const char* hostname, const int port, struct sockaddr_in* serv){ /* [0] Initialization @@ -91,7 +153,7 @@ int xconnect(const char* hostname, const int port, struct sockaddr_in* serv){ /* [1] Create xsocket =========================================================*/ /* (1) Create UPD xsocket */ - xsocket = socket(AF_INET, SOCK_DGRAM, 0); + xsocket = socket(AF_INET, SOCK_STREAM, 0); DEBUG&& debug("xconnect", "creating client socket"); /* (r2-) Manage error */ @@ -156,7 +218,7 @@ int xlisten(const int xsocket, struct sockaddr_in *client, char* buffer, int buf /* (2) Listen */ DEBUG&& debug("xlisten", "waiting for data"); - int read = recvfrom(xsocket, buffer, bufsize / sizeof(char) + sizeof(char), 0, (struct sockaddr*) client, &sock_len); + int read = listen(xsocket, 1); /* (3) Manage error */ if( read == -1 ){