1 /****************************************************************
3 * Program SimpleEchoTCPClient:
4 * Simple TCP client for echo service (port 7)
6 * Author: Simone Piccardi
9 * Usage: echo -h give all info's
11 * $Id: SimpleEchoTCPClient.c,v 1.3 2001/06/17 21:58:46 piccardi Exp $
13 ****************************************************************/
15 * Include needed headers
17 #include <sys/types.h> /* predefined types */
18 #include <unistd.h> /* include unix standard library */
19 #include <arpa/inet.h> /* IP addresses conversion utiliites */
20 #include <sys/socket.h> /* socket library */
21 #include <stdio.h> /* include standard I/O library */
27 void EchoClient(FILE * filein, int socket);
30 int main(int argc, char *argv[])
33 * Variables definition
36 struct sockaddr_in serv_add;
38 * Input section: decode parameters passed in the calling
41 opterr = 0; /* don't want writing to stderr */
42 while ( (i = getopt(argc, argv, "h")) != -1) {
48 printf("Wrong -h option use\n");
52 case '?': /* unrecognized options */
53 printf("Unrecognized options -%c\n",optopt);
55 default: /* should not reached */
59 /* ***********************************************************
61 * Options processing completed
65 * ***********************************************************/
67 if ( (sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
68 perror("Socket creation error");
71 /* initialize address */
72 memset((void *) &serv_add, 0, sizeof(serv_add)); /* clear server address */
73 serv_add.sin_family = AF_INET; /* address type is INET */
74 serv_add.sin_port = htons(7); /* echo port is 7 */
75 /* build address using inet_pton */
76 if ( (inet_pton(AF_INET, argv[optind], &serv_add.sin_addr)) <= 0) {
77 perror("Address creation error");
80 /* extablish connection */
81 if (connect(sock_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
82 perror("Connection error");
85 /* read daytime from server */
86 EchoClient(stdin, sock_fd);
91 * routine to print usage info and exit
94 printf("Take daytime from a remote host \n");
96 printf(" daytime [-h] [-v] [host in dotted decimal form] \n");
97 printf(" -v set verbosity on\n");
98 printf(" -h print this help\n");
102 void EchoClient(FILE * filein, int socket)
104 char sendbuff[MAXLINE], recvbuff[MAXLINE];
106 while (fgets(sendbuff, MAXLINE, filein) != NULL) {
107 SockWrite(socket, sendbuff, strlen(sendbuff));
108 nread = SockRead(socket, recvbuff, strlen(sendbuff));
110 fputs(recvbuff, stdout);