2 * Test name: test04_srv.c
4 * Objective: Test a simple UDP server
6 * Description: Implements a simple echo server using the UDP 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>
21 #include <net/netlib.h>
22 #include <net/gen/netdb.h>
23 #include <net/gen/in.h>
24 #include <net/gen/udp.h>
25 #include <net/gen/udp_hdr.h>
26 #include <net/gen/udp_io.h>
31 /* type for received data */
38 int udp_conf(long port
) {
44 /* Get default UDP device */
45 if ((udp_device
= getenv("UDP_DEVICE")) == NULL
)
46 udp_device
= UDP_DEVICE
;
48 /* Open UDP connection */
49 if ((netfd
= open(udp_device
, O_RDWR
)) < 0)
51 fprintf(stderr
,"Error opening UDP connection\n");
55 /* Configure UDP connection */
56 udpopt
.nwuo_flags
= NWUO_COPY
| NWUO_LP_SET
| NWUO_EN_LOC
| NWUO_DI_BROAD
57 | NWUO_RP_ANY
| NWUO_RA_ANY
| NWUO_RWDATALL
| NWUO_DI_IPOPT
;
59 udpopt
.nwuo_locport
= (udpport_t
) htons(port
);
61 if ((ioctl(netfd
, NWIOSUDPOPT
, &udpopt
))<0)
63 fprintf(stderr
,"Error configuring the connection\n");
68 /* Get conf options */
69 if ((ioctl(netfd
, NWIOGUDPOPT
, &udpopt
))<0)
71 fprintf(stderr
,"Error getting the conf\n");
79 int main(int argc
,char *argv
[]) {
88 if ((fd
= udp_conf(PORT
)) < 0) {
89 fprintf(stderr
, "Error configuring UDP connection\n");
92 printf("Waiting for messages on port: %ld\n", PORT
);
94 /* Initialize fd_set */
96 FD_SET(fd
, &fds_read
);
100 /* Wait for data available to be read (no timeout) */
101 ret
= select(4, &fds_read
, NULL
, NULL
, NULL
);
103 fprintf(stderr
, "Error on select: %d", errno
);
106 if (!FD_ISSET(fd
, &fds_read
)) {
107 printf("Error: network fd is not ready (?)\n");
110 printf("Ready to receive...\n");
111 /* Read received data */
112 data_read
= read(fd
, &buffer
, sizeof(udp_buffer_t
));
113 printf("Received data: %s\n", buffer
.data
);
115 /* Can exit if the received string == exit */
116 if (!strcmp(buffer
.data
,"exit"))
119 /* Send data back, swap addresses */
120 tmp_addr
= buffer
.header
.uih_src_addr
;
121 buffer
.header
.uih_src_addr
= buffer
.header
.uih_dst_addr
;
122 buffer
.header
.uih_dst_addr
= tmp_addr
;
125 tmp_port
= buffer
.header
.uih_src_port
;
126 buffer
.header
.uih_src_port
= buffer
.header
.uih_dst_port
;
127 buffer
.header
.uih_dst_port
= tmp_port
;
129 /* Write the same back */
130 write(fd
, &buffer
, data_read
);