/*#include #include #include */ #include #include #include #include #include /*SYNTAX ./clientUDPs (host) */ char PORT[] = "47200"; int main(int argc, char * argv[]) { int n, s; char buf[1024]; char hostname[64]; struct addrinfo hints, *result, *tmp; memset(&hints, 0, sizeof(hints)); /*It is important reset all to NULL*/ switch(argc) { case 1: /* Get our local host name. */ gethostname(hostname, sizeof(hostname)); break; case 2: /* Get name from command line */ strcpy(hostname, argv[1]); break; default: printf("Usage: %s [server_name]\n",argv[0]); exit(-1); } hints.ai_family = AF_INET; //IPv4 hints.ai_socktype = SOCK_DGRAM; //UDP if ((getaddrinfo(hostname, 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 connect. If socket (or connect) 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 (connect(s, tmp->ai_addr, tmp->ai_addrlen) != -1) break; /* Success */ close(s); } freeaddrinfo(result); /* No longer needed */ if (tmp == NULL) { /*No address succeeded*/ fprintf(stderr, "Could not connect\n"); exit(EXIT_FAILURE); } /* Read from standard input, and copy the * data to the socket. */ while ((n = read(0, buf, sizeof(buf))) > 0) sendto(s, buf, n, 0, tmp -> ai_addr, tmp -> ai_addrlen); /* We could also use just send or write */ /*send(s, buf, n, 0); */ /* send an empty message to close the server*/ sendto(s, buf, 0, 0, tmp -> ai_addr, tmp -> ai_addrlen); close(s); exit(0); }