Remove unused pkg dependancy
[platform/upstream/iotivity.git] / extlibs / tinydtls / tests / dsrv-test.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <errno.h>
4 #include <netinet/in.h>
5 #include <sys/types.h>
6 #include <sys/socket.h>
7 #include <sys/time.h>
8
9 #include "dsrv.h" 
10
11 void
12 handle_read(struct dsrv_context_t *ctx) {
13   int len;
14   static char buf[200];
15   struct sockaddr_storage src;
16   socklen_t srclen = sizeof(src);
17   int fd = dsrv_get_fd(ctx, DSRV_READ);
18
19   len = recvfrom(fd, buf, sizeof(buf), 0, 
20                  (struct sockaddr *)&src, &srclen);
21
22   if (len < 0) {
23     perror("recvfrom");
24   } else {
25     printf("read %d bytes: '%*s'\n", len, len, buf);
26     if (dsrv_sendto(ctx, (struct sockaddr *)&src, srclen, 0, buf, len) 
27         == NULL) {
28       fprintf(stderr, "cannot add packet to sendqueue\n");
29     }
30   }
31 }
32
33 int
34 handle_write(struct dsrv_context_t *ctx) {
35   struct packet_t *p;
36   int fd = dsrv_get_fd(ctx, DSRV_WRITE);
37   int len;
38
39   p = ctx->rq ? nq_peek(ctx->wq) : NULL;
40
41   if (!p)
42     return -1;
43
44   len = sendto(fd, p->buf, p->len, 0, p->raddr, p->rlen);
45   
46   if (len < 0)
47     perror("sendto");
48   else 
49     nq_pop(ctx->wq);
50
51   return len;
52 }
53
54 int main(int argc, char **argv) {
55
56 #if 1
57   struct sockaddr_in6 listen_addr = { AF_INET6, htons(20220), 0, IN6ADDR_ANY_INIT, 0 };
58 #else
59   struct sockaddr_in listen_addr = { AF_INET, htons(20220), { htonl(0x7f000001) } };
60 #endif
61   fd_set rfds, wfds;
62   struct timeval timeout;
63   struct dsrv_context_t *ctx;
64   int result;
65
66   ctx = dsrv_new_context((struct sockaddr *)&listen_addr, sizeof(listen_addr), 
67                          200,200);
68
69   if (!ctx) {
70     fprintf(stderr, "E: cannot create server context\n");
71     return -1;
72   }
73
74   while (1) {
75     FD_ZERO(&rfds);
76     FD_ZERO(&wfds);
77
78     dsrv_prepare(ctx, &rfds, DSRV_READ);
79     dsrv_prepare(ctx, &wfds, DSRV_WRITE);
80     
81 #if 0
82     timeout.tv_sec = 0;
83     timeout.tv_usec = dsrv_get_timeout(ctx);
84 #else
85     timeout.tv_sec = 5;
86     timeout.tv_usec = 0;
87 #endif
88     
89     result = select( FD_SETSIZE, &rfds, &wfds, 0, &timeout);
90     
91     if (result < 0) {           /* error */
92       if (errno != EINTR)
93         perror("select");
94     } else if (result == 0) {   /* timeout */
95       printf(".");              
96     } else {                    /* ok */
97       if (dsrv_check(ctx, &wfds, DSRV_WRITE))
98         handle_write(ctx);
99       else if (dsrv_check(ctx, &rfds, DSRV_READ))
100         handle_read(ctx);
101     }
102   }
103
104   dsrv_close(ctx);
105   dsrv_free_context(ctx);
106
107   return 0;
108 }