2 * Test name: test06_cli.c
4 * Objective: Test a simple TCP client
6 * Description: Implements a simple echo client using the TCP protocol. First
7 * it waits until it is possible to write (which is always).
10 #include <sys/types.h>
11 #include <sys/ioctl.h>
12 #include <sys/select.h>
20 #include <net/netlib.h>
21 #include <net/gen/netdb.h>
22 #include <net/gen/in.h>
23 #include <net/gen/tcp.h>
24 #include <net/gen/tcp_io.h>
29 int tcp_connect(char *host
, long port
)
31 /* creates a tcp connection with specified host and port */
36 nwio_tcpconf_t tcpconf
;
41 /* get host address */
42 if ((hp
= gethostbyname(host
)) == (struct hostent
*) NULL
)
44 fprintf(stderr
,"Unknown host\n");
47 memcpy((char *)&dirhost
, (char *)hp
->h_addr
, hp
->h_length
);
49 /* Get default TCP device */
50 if (( tcp_device
= getenv("TCP_DEVICE") ) == NULL
)
51 tcp_device
= TCP_DEVICE
;
53 /* Establish TCP connection */
54 if ((netfd
= open(tcp_device
, O_RDWR
)) < 0)
56 fprintf(stderr
,"Error opening TCP device\n");
60 /* Configure TCP connection */
61 tcpconf
.nwtc_flags
=NWTC_LP_SEL
| NWTC_SET_RA
| NWTC_SET_RP
;
62 tcpconf
.nwtc_remaddr
= dirhost
;
63 tcpconf
.nwtc_remport
= (tcpport_t
) htons(port
);
65 if ((result
= ioctl(netfd
, NWIOSTCPCONF
, &tcpconf
) ) <0)
67 fprintf(stderr
, "Error establishing communication\n");
68 printf("Error: %d\n",result
);
73 /* Get configuration for TCP comm */
74 if ((result
= ioctl(netfd
, NWIOGTCPCONF
, &tcpconf
) ) < 0)
76 fprintf(stderr
,"Error getting configuration\n");
77 printf("Error: %d\n", result
);
82 /* Establish connection */
83 tcpcopt
.nwtcl_flags
= 0;
86 if ( (result
= ioctl(netfd
, NWIOTCPCONN
, &tcpcopt
)) < 0 ) {
89 fprintf(stderr
, "Server is not listening\n");
93 fprintf(stderr
, "Unable to connect\n");
98 break; /* Connection */
100 /* Check result value */
102 fprintf(stderr
, "Error connecting\n");
103 fprintf(stderr
, "Error: %d\n", result
);
104 printf("Number of tries: %d\n", tries
);
105 printf("Error: %d\n", errno
);
112 int main(int argc
,char *argv
[]) {
120 /* Check parameters */
122 fprintf(stderr
,"Usage: %s host\n", argv
[0]);
126 if ((fd
= tcp_connect(argv
[1], PORT
) ) < 0)
128 printf("Connected to server\n");
131 FD_SET(fd
, &fds_write
);
134 /* Wait until it is possible to write with select */
135 ret
= select(4, NULL
, &fds_write
, NULL
, NULL
);
137 fprintf(stderr
, "Error on select waiting for write: %d\n", errno
);
140 if (!FD_ISSET(fd
, &fds_write
)) {
141 fprintf(stderr
, "Error: The net connection is not ready for writing (?)\n");
145 /* Get a string and send it */
146 printf("Ready to write...\n");
147 printf("Send data: ");
149 write(fd
, &send_buf
, strlen(send_buf
)+1);
151 /* If data sent is exit then break */
152 if (!strcmp(send_buf
,"exit"))
155 /* Get server response */
156 data_read
= read(fd
, &recv_buf
, 1024);
157 printf("Received: %s\n\n", recv_buf
);
160 /* Close TCP communication */