2 * Test name: test04_cli.c
4 * Objective: Test a simple UDP client
6 * Description: Implements a simple echo client using the UDP 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/udp.h>
24 #include <net/gen/udp_hdr.h>
25 #include <net/gen/udp_io.h>
30 /* Type for received data */
37 int udp_conf(char *host
, long port
, udp_io_hdr_t
*header
)
39 /* configures UDP connection */
47 /* get host address */
48 if ((hp
= gethostbyname(host
)) == (struct hostent
*) NULL
)
50 fprintf(stderr
,"Unknown host\n");
53 memcpy((char *)&dirhost
, (char *)hp
->h_addr
, hp
->h_length
);
56 if (( udp_device
= getenv("UDP_DEVICE") ) == NULL
)
57 udp_device
= UDP_DEVICE
;
59 /* Get UDP connection */
60 if ((netfd
= open(udp_device
, O_RDWR
)) < 0)
62 fprintf(stderr
,"Error opening UDP device\n");
66 /* Configure UDP connection */
67 udpopt
.nwuo_flags
= NWUO_COPY
| NWUO_LP_SEL
| NWUO_EN_LOC
| NWUO_DI_BROAD
68 | NWUO_RP_SET
| NWUO_RA_SET
| NWUO_RWDATALL
| NWUO_DI_IPOPT
;
69 udpopt
.nwuo_remaddr
= dirhost
;
70 udpopt
.nwuo_remport
= (udpport_t
) htons(port
);
72 if ((result
= ioctl(netfd
, NWIOSUDPOPT
, &udpopt
) ) <0)
74 fprintf(stderr
, "Error establishing communication\n");
75 printf("Error: %d\n",result
);
80 /* Get configuration for UDP comm */
81 if ((result
= ioctl(netfd
, NWIOGUDPOPT
, &udpopt
) ) < 0)
83 fprintf(stderr
,"Error getting configuration\n");
84 printf("Error: %d\n", result
);
89 header
->uih_src_addr
= udpopt
.nwuo_locaddr
;
90 header
->uih_dst_addr
= udpopt
.nwuo_remaddr
;
91 header
->uih_src_port
= udpopt
.nwuo_locport
;
92 header
->uih_dst_port
= udpopt
.nwuo_remport
;
97 int main(int argc
,char *argv
[]) {
100 udp_buffer_t buffer_send
, buffer_rec
;
104 /* Check parameters */
106 fprintf(stderr
,"Usage: %s host\n", argv
[0]);
110 if ((fd
= udp_conf(argv
[1], PORT
, &buffer_send
.header
) ) < 0)
115 FD_SET(fd
, &fds_write
);
119 /* Wait until it is possible to write with select */
121 ret
= select(4, NULL
, &fds_write
, NULL
, NULL
);
123 fprintf(stderr
, "Error on select waiting for write: %d\n", errno
);
126 if (!FD_ISSET(fd
, &fds_write
)) {
127 fprintf(stderr
, "Error: The net connection is not ready for writing (?)\n");
131 /* Get a string and send it */
132 printf("Ready to write...\n");
133 printf("Send data: ");
134 gets(buffer_send
.data
);
135 write(fd
, &buffer_send
, sizeof(udp_buffer_t
));
137 /* If data sent is exit then break */
138 if (!strcmp(buffer_send
.data
,"exit"))
141 /* Get server response */
142 data_read
= read(fd
, &buffer_rec
, sizeof(udp_buffer_t
));
143 printf("Received: %s\n\n", buffer_rec
.data
);
146 /* Close UDP communication */