#include #include #include #include #include #include #include #include #include #include #define PORT 3490 #define MAXDATASIZE 100 int main(int argc, char *argv[]) { int sockfd, numbytes, err; char buf[MAXDATASIZE]; struct sockaddr_in their_addr; struct addrinfo hints, *res; if (argc != 2) { fprintf(stderr,"usage: client host\n"); exit(1); } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } their_addr.sin_family = AF_INET; their_addr.sin_port = htons(PORT); /* Set hits */ memset( &hints, 0, sizeof( hints ) ); hints.ai_family = PF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags |= AI_CANONNAME; /* Look up address */ if ( ( err = getaddrinfo( argv[ 1 ], NULL, &hints, &res ) ) != 0 ) printf( "getaddrinfo: %s\n", gai_strerror( err ) ); else { char host[ NI_MAXHOST ]; struct addrinfo *i = res; #ifdef DEBUG printf( "'%s' has the following IP " \ "addresses translations:\n", argv[ 1 ] ); while ( i ) { inet_ntop( i->ai_family, &((struct sockaddr_in *) i->ai_addr)->sin_addr, host, NI_MAXHOST ); printf( " >%s (%s)\n", host, i->ai_canonname ); i = i->ai_next; } inet_ntop( res->ai_family, &((struct sockaddr_in *) res->ai_addr)->sin_addr, host, NI_MAXHOST ); printf( "Setting IP to %s\n", host ); #endif memcpy( &their_addr.sin_addr, &((struct sockaddr_in *) res->ai_addr)->sin_addr, sizeof( struct in_addr ) ); freeaddrinfo( res ); } memset(&(their_addr.sin_zero), '\0', 8); if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) { perror("connect"); exit(1); } if ((numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv"); exit(1); } buf[numbytes] = '\0'; printf("Received: %s",buf); close(sockfd); return 0; } /* author: Gustavo Sverzut Barbieri (http://www.gustavobarbieri.com.br) */