#include #include #include #include #include #include #include //addrinfo #include /*SYNTAX ./serverUDPs */ char PORT[] = "47200"; int main(void) { char buf[50]; int s, n; 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_DGRAM; //UDP 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); } /* Read from the socket until end-of-file and * print what we get on the standard output. * "We receive mail, open it, and show it to everyone" */ while ((n = recv(s, buf, sizeof(buf), 0)) > 0) write(1, buf, n); close(s); exit(0); }