2 * Test name: test06_srv.c
4 * Objective: Test a simple TCP server
6 * Description: Implements a simple echo server using the TCP protocol. Instead
7 * of blocking on read(), it performs a select call first blocking there
8 * until there is data to be read
11 #include <sys/types.h>
12 #include <sys/ioctl.h>
13 #include <sys/select.h>
22 #include <net/netlib.h>
23 #include <net/gen/netdb.h>
24 #include <net/gen/in.h>
25 #include <net/gen/tcp.h>
26 #include <net/gen/tcp_io.h>
28 #include <net/gen/inet.h>
32 int my_listen(long port
) {
36 nwio_tcpconf_t tcpconf
;
37 nwio_tcpcl_t tcplistenopt
;
39 /* Get default UDP device */
40 if ((tcp_device
= getenv("TCP_DEVICE")) == NULL
)
41 tcp_device
= TCP_DEVICE
;
43 /* Open TCP connection */
44 if ((netfd
= open(tcp_device
, O_RDWR
)) < 0)
46 fprintf(stderr
,"Error opening TCP connection\n");
50 /* Configure TCP connection */
51 tcpconf
.nwtc_flags
= NWTC_LP_SET
| NWTC_UNSET_RA
| NWTC_UNSET_RP
;
52 tcpconf
.nwtc_locport
= (tcpport_t
) htons(port
);
54 if ((ioctl(netfd
, NWIOSTCPCONF
, &tcpconf
))<0)
56 fprintf(stderr
,"Error configuring the connection\n");
61 /* Get communication options */
62 if ((ioctl(netfd
, NWIOGTCPCONF
, &tcpconf
)) < 0) {
63 fprintf(stderr
, "Error getting configuration\n");
68 /* Set conf options */
69 tcplistenopt
.nwtcl_flags
= 0;
70 printf("Waiting for connections...\n");
71 while ((ioctl(netfd
, NWIOTCPLISTEN
, &tcplistenopt
)) == -1)
75 fprintf(stderr
,"Unable to listen for connections\n");
83 int main(int argc
,char *argv
[]) {
90 if ((fd
= my_listen(PORT
)) < 0) {
93 printf("Waiting for messages on port: %ld\n", PORT
);
95 /* Initialize fd_set */
97 FD_SET(fd
, &fds_read
);
101 /* Wait for data available to be read (no timeout) */
103 ret
= select(4, &fds_read
, NULL
, NULL
, NULL
);
105 fprintf(stderr
, "Error on select: %d\n", errno
);
108 if (!FD_ISSET(fd
, &fds_read
)) {
109 printf("Error: network fd is not ready (?)\n");
113 printf("Ready to receive...\n");
114 /* Read received data */
115 data_read
= read(fd
, &buffer
, 1024);
116 printf("Received data: %s\n", buffer
);
118 /* Can exit if the received string == exit */
119 if (!strcmp(buffer
,"exit"))
122 /* Write the same back */
123 write(fd
, &buffer
, data_read
);
125 printf("Connection finished\n");