Created
May 13, 2015 12:23
-
-
Save booo/908e4c29f17c33f17347 to your computer and use it in GitHub Desktop.
(minimal) libcoap client example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "libcoap/coap.h" | |
#include <arpa/inet.h> | |
#include <stdio.h> | |
int main() { | |
struct sockaddr_in6 sa_dst; | |
// clear memory | |
memset(&sa_dst, 0, sizeof(struct sockaddr_in6 )); | |
// write byte representation to sin6_addr | |
inet_pton(AF_INET6, "::1", &(sa_dst.sin6_addr)); | |
// set network family to ipv6 | |
sa_dst.sin6_family = AF_INET6; | |
// set port to COAP_DEFAULT_PORT | |
sa_dst.sin6_port = htons(COAP_DEFAULT_PORT); | |
coap_address_t coap_dst; | |
coap_address_init(&coap_dst); | |
coap_dst.size = sizeof(struct sockaddr_in6); // is this right? | |
coap_dst.addr.sin6 = sa_dst; // is this right? | |
// create src address | |
struct sockaddr_in6 sa_src; | |
// clear memory | |
memset(&sa_src, 0, sizeof(struct sockaddr_in6)); | |
// write byte representation to sin6_addr | |
// source of package is localhost aka ::1 | |
inet_pton(AF_INET6, "::1", &(sa_src.sin6_addr)); | |
// set network family to ipv6 | |
sa_src.sin6_family = AF_INET6; | |
// set src port to 8888 TODO how do we find a good source port? | |
sa_src.sin6_port = htons(8888); | |
coap_address_t coap_src; | |
coap_address_init(&coap_src); | |
coap_src.size = sizeof(struct sockaddr_in6); // is this right? | |
coap_src.addr.sin6 = sa_src; // is this right? | |
// create context from src address | |
coap_context_t *context = NULL; | |
context = coap_new_context(&coap_src); | |
// send the request | |
const unsigned char payload[20] = "Hello World"; | |
coap_pdu_t *pdu; | |
pdu = coap_pdu_init(COAP_MESSAGE_NON, 0x01, COAP_INVALID_TID, 128); | |
if(pdu == NULL) { | |
printf("Somthing went wrong in pdu_init\n"); | |
// something went wrong | |
return 1; | |
} | |
// do not add payload for now | |
// coap_add_data(pdu, 12, payload); | |
coap_send(context, context->endpoint, &coap_dst, pdu); | |
coap_delete_pdu(pdu); | |
coap_free_context(context); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment