#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, sr; char buf[MAXDATASIZE]; struct sockaddr_in their_addr; fd_set readfds, rds; char sbuf[MAXDATASIZE]; int sbuf_pos=0; if (argc != 2) { fprintf(stderr,"usage: client hostip\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); if (inet_pton(AF_INET, argv[1], &their_addr.sin_addr) <= 0) { perror("inet_pton"); exit(1); } memset(&(their_addr.sin_zero), '\0', 8); if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) { perror("connect"); exit(1); } FD_ZERO( &readfds ); FD_SET( 0, &readfds ); FD_SET( sockfd, &readfds ); while ( 1 ) { rds = readfds; sr = select( sockfd + 1, &rds, NULL, NULL, NULL ); if ( sr == -1 ) perror( "select" ); else if ( sr ) { /* Data from standard input ? */ if ( FD_ISSET( 0, &rds ) ) { char input; int r; if ( ( r = read( 0, &input, 1 ) ) == 1 ) { if ( send( sockfd, &input, 1, 0 ) == -1 ) { perror( "send" ); exit( -1 ); } } else if ( r == 0 ) break; } /* Data from socket ? */ else if ( FD_ISSET( sockfd, &rds ) ) { char input; if ( ( numbytes = recv( sockfd, &input, 1, 0 ) ) == -1 ) { perror( "recv" ); exit( -1 ); } else if ( numbytes == 0 ) { puts( "Connection closed by peer.\n" ); break; } else { putchar( input ); } } } } close(sockfd); return 0; } /* author: Gustavo Sverzut Barbieri (http://www.gustavobarbieri.com.br) */