/* Lab. Calcolo II - Esempio di codice Example code: socket listen and receive demonstration (uses shelper calls) (20000818 prelz@mi.infn.it) */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/socket.h> int main (int argc, char *argv[]) { char prov_host[80]; char *message = NULL; int allocated_size = 0; char buffer[80]; int listen_port = 1313; int read_chars; int recv_chars; int s; printf("Listening for messages...\n"); s = SHLP_listen_and_connect(listen_port, 0, prov_host, sizeof(prov_host)); if (s<0) { fprintf(stderr,"Couldn't accept a connection on port %d\n", listen_port); exit(1); } /* In general we cannot assume we know the size of the message */ /* we are waiting for */ read_chars = 0; while ((recv_chars = recv(s,buffer,sizeof(buffer),0)) > 0) { if ((read_chars + recv_chars) > allocated_size) { /* We increase the allocated size by a "buffer"-sized chunk */ allocated_size += sizeof(buffer)+1; message = (char *)realloc(message,allocated_size); if (message == NULL) { allocated_size = 0; perror("Error allocating buffer for incoming message"); close(s); exit(1); } } memcpy(&message[read_chars],buffer,recv_chars); read_chars += recv_chars; /* Make sure we have a terminating NULL */ message[read_chars] = '\000'; } if (recv_chars < 0) { fprintf(stderr,"Error receiving message."); close(s); exit(1); } printf("Received a message from <%s>:\n", prov_host); printf("%s\n", message); close(s); exit(0); }