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 ) {
29 static unsigned char buf[20];
32 if ( ! ( pdu = coap_new_pdu() ) )
35 pdu->hdr->type = COAP_MESSAGE_NON;
36 pdu->hdr->code = COAP_REQUEST_POST;
37 pdu->hdr->id = htons(id++);
39 enc = COAP_PSEUDOFP_ENCODE_8_4_DOWN(value,ls);
40 coap_add_data( pdu, 1, &enc);
42 len = sprintf((char *)buf, "%u", COAP_PSEUDOFP_DECODE_8_4(enc));
44 coap_add_data( pdu, len, buf );
51 usage( const char *program ) {
54 p = strrchr( program, '/' );
58 fprintf( stderr, "%s -- tiny fake sensor\n"
59 "(c) 2010 Olaf Bergmann <bergmann@tzi.org>\n\n"
60 "usage: %s [group address]\n"
61 "\n\nSends some fake sensor values to specified multicast group\n",
66 get_context(const char *node, const char *port) {
67 coap_context_t *ctx = NULL;
69 struct addrinfo hints;
70 struct addrinfo *result, *rp;
72 memset(&hints, 0, sizeof(struct addrinfo));
73 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
74 hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */
75 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV | AI_ALL;
77 s = getaddrinfo(node, port, &hints, &result);
79 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
83 /* iterate through results until success */
84 for (rp = result; rp != NULL; rp = rp->ai_next) {
85 ctx = coap_new_context(rp->ai_addr, rp->ai_addrlen);
87 /* TODO: output address:port for successful binding */
92 fprintf(stderr, "no context available for interface '%s'\n", node);
100 main(int argc, char **argv) {
104 struct sockaddr_in6 dst;
107 if ( argc > 1 && strncmp(argv[1], "-h", 2) == 0 ) {
112 ctx = get_context("::", NULL);
116 id = rand() & INT_MAX;
118 memset(&dst, 0, sizeof(struct sockaddr_in6 ));
119 dst.sin6_family = AF_INET6;
120 inet_pton( AF_INET6, argc > 1 ? argv[1] : "::1", &dst.sin6_addr );
121 dst.sin6_port = htons( COAP_DEFAULT_PORT );
123 if ( IN6_IS_ADDR_MULTICAST(&dst.sin6_addr) ) {
124 /* set socket options for multicast */
126 if ( setsockopt( ctx->sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
127 (char *)&hops, sizeof(hops) ) < 0 )
128 perror("setsockopt: IPV6_MULTICAST_HOPS");
134 if (! (pdu = make_pdu( rand() & 0xfff ) ) )
137 coap_send( ctx, (struct sockaddr *)&dst, sizeof(dst), pdu );
138 coap_delete_pdu(pdu);
140 tv.tv_sec = 5; tv.tv_usec = 0;
142 select( 0, 0, 0, 0, &tv );
146 coap_free_context( ctx );