/* A simple echo client using TCP from Leon-Garcia and Widjaja's book "Communication Networks: Fundamental Concepts and Key Architectures," McGraw-Hill, 2000, pages 72 - 74. */ #include #include /* for gethostbyname() */ #include #include #include #define SERVER_TCP_PORT 3000 /* well known port */ #define BUFLEN 256 /* buffer length */ int main (int argc, char **argv) { int n, bytes_to_read; int sd, port; struct hostent *hp; struct sockaddr_in server; char *host, *bp, rbuf[BUFLEN], sbuf[BUFLEN]; switch(argc) { case 2: host = argv[1]; port = SERVER_TCP_PORT; break; case 3: host = argv[1]; port = atoi(argv[2]); break; default: fprintf(stderr, "Usage: %s host [port]\n", argv[0]); exit(1); } /* Create a stream socket (TCP, connection-oriented) */ if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { fprintf(stderr, "%s: Can't create a socket.\n", argv[0]); exit(1); } /* Bind an address to the socket */ bzero((char *)&server, sizeof(struct sockaddr_in)); server.sin_family = AF_INET; /* Internet connection */ server.sin_port = htons(port); /* Define the port # */ if ((hp = gethostbyname(host)) == NULL) { fprintf(stderr, "%s: Can't get server's address.\n", argv[0]); exit(1); } bcopy(hp->h_addr, (char *)&server.sin_addr, hp->h_length); /* Connecting to the server */ if (connect(sd, (struct sockaddr *)&server, sizeof(server)) == -1) { fprintf(stderr, "%s: Can't connect to server.\n", argv[0]); exit(1); } printf("%s: Connected to server %s.\n", argv[0], hp->h_name); printf("%s: String to transmit? ", argv[0]); /* Prompt user for a string */ gets(sbuf); /* Read user input string */ write(sd, sbuf, BUFLEN); /* Send string to echo server */ printf("%s: String received = ", argv[0]); bp = rbuf; bytes_to_read = BUFLEN; while ((n = read(sd, bp, bytes_to_read)) > 0) { bp += n; bytes_to_read -= n; } printf("%s\n", rbuf); close(sd); return(0); }