#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 reset all to NULL*/ hints.ai_family = AF_INET; //IPv4 hints.ai_socktype = SOCK_STREAM; //TCP hints.ai_flags = AI_PASSIVE; //Use the wildcard address if ((getaddrinfo(NULL, PORT, &hints, &result)) != 0) /*Checking status of getaddrinfo result*/ { fprintf(stderr, "getaddrinfo error\n"); exit(EXIT_FAILURE); } /* getaddrinfo() returns 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); /* Read from the socket until end-of-file and * print what we get on the standard output. */ inet_ntop(AF_INET, &(((struct sockaddr_in *)&from_addr)->sin_addr), ip, sizeof(ip)); //Convert Ipv4 to string 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); }