#include #include #include #include #include #include #include #include #include //addrinfo /*SYNTAX ./serverTCPs */ char PORT[] = "47200"; #define BUF_SIZE 500 int main(void) { char buf[BUF_SIZE]; int s, n, ns; struct sockaddr_storage from_addr; socklen_t from_addr_len; unsigned char ip[50] = ""; struct addrinfo hints, *result, *tmp; memset(&hints, 0, sizeof(hints)); /*It is important to reset all to NULL*/ hints.ai_family = AF_INET; //IPv4, AF_INET6, o AF_UNSPEC hints.ai_socktype = SOCK_STREAM; //TCP (other values: SOCK_DGRAM or 0) hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV; //Wildcard IP address, service name is numeric if ((getaddrinfo(NULL, PORT, &hints, &result)) != 0) /*Checking status of getaddrinfo result*/ { fprintf(stderr, "getaddrinfo error\n"); exit(EXIT_FAILURE); } /* getaddrinfo() returns in "result" a list of address structures. Try each address until we successfully bind. If socket (or bind) fails, we (close the socket and) try the next address. */ for (tmp = result; tmp != NULL; tmp = tmp -> ai_next) { s = socket(tmp->ai_family, tmp->ai_socktype, tmp->ai_protocol); if (s == -1) continue; if (bind(s, tmp -> ai_addr, tmp -> ai_addrlen) == 0) break; //Success close(s); } freeaddrinfo(result); //No longer needed if (tmp == NULL) { fprintf(stderr, "Could not bind\n"); exit(EXIT_FAILURE); } /* Listen for connections. */ listen(s, 5); /* Accept a connection. */ from_addr_len = sizeof(from_addr); ns = accept(s, (struct sockaddr *)&from_addr, &from_addr_len); //Convert IPv4 address to string (presentation layer) inet_ntop(AF_INET, &(((struct sockaddr_in *)&from_addr)->sin_addr), ip, sizeof(ip)); /* Read from the socket until end-of-file and * print what we get on the standard output. */ while ((n = recv(ns, buf, sizeof(buf), 0)) > 0){ buf[n] = '\0'; printf("Connection from: %s \nMessage: %s\n", ip, buf);} close(ns); close(s); exit(0); }