3 * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
5 * This file is part of the CoAP library libcoap. Please see
6 * README for terms of use.
14 #include <sys/select.h>
15 #include <sys/types.h>
16 #include <sys/socket.h>
17 #include <netinet/in.h>
18 #include <arpa/inet.h>
26 make_pdu(unsigned int value)
30 static unsigned char buf[20];
33 if (!(pdu = coap_new_pdu()))
36 pdu->hdr->type = COAP_MESSAGE_NON;
37 pdu->hdr->code = COAP_REQUEST_POST;
38 pdu->hdr->id = htons(id++);
40 enc = COAP_PSEUDOFP_ENCODE_8_4_DOWN(value,ls);
41 coap_add_data(pdu, 1, &enc);
43 len = snprintf((char *) buf, sizeof(buf), "%u", COAP_PSEUDOFP_DECODE_8_4(enc));
46 coap_add_data(pdu, len, buf);
52 void usage(const char *program)
56 p = strrchr(program, '/');
60 fprintf(stderr, "%s -- tiny fake sensor\n"
61 "(c) 2010 Olaf Bergmann <bergmann@tzi.org>\n\n"
62 "usage: %s [group address]\n"
63 "\n\nSends some fake sensor values to specified multicast group\n", program, program);
67 get_context(const char *node, const char *port)
69 coap_context_t *ctx = NULL;
71 struct addrinfo hints;
72 struct addrinfo *result, *rp;
74 memset(&hints, 0, sizeof(struct addrinfo));
75 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
76 hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */
77 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV | AI_ALL;
79 s = getaddrinfo(node, port, &hints, &result);
82 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
86 /* iterate through results until success */
87 for (rp = result; rp != NULL; rp = rp->ai_next)
89 ctx = coap_new_context(rp->ai_addr, rp->ai_addrlen);
92 /* TODO: output address:port for successful binding */
97 fprintf(stderr, "no context available for interface '%s'\n", node);
99 finish: freeaddrinfo(result);
103 int main(int argc, char **argv)
108 struct sockaddr_in6 dst;
111 if (argc > 1 && strncmp(argv[1], "-h", 2) == 0)
117 ctx = get_context("::", NULL);
121 id = rand() & INT_MAX;
123 memset(&dst, 0, sizeof(struct sockaddr_in6));
124 dst.sin6_family = AF_INET6;
125 inet_pton(AF_INET6, argc > 1 ? argv[1] : "::1", &dst.sin6_addr);
126 dst.sin6_port = htons(COAP_DEFAULT_PORT);
128 if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr))
130 /* set socket options for multicast */
132 if (setsockopt(ctx->sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *) &hops, sizeof(hops))
134 perror("setsockopt: IPV6_MULTICAST_HOPS");
141 if (!(pdu = make_pdu(rand() & 0xfff)))
144 coap_send(ctx, (struct sockaddr *) &dst, sizeof(dst), pdu);
145 coap_delete_pdu(pdu);
150 select(0, 0, 0, 0, &tv);
154 coap_free_context(ctx);