libcoap  4.1.1
 All Data Structures Files Functions Variables Typedefs Macros Groups Pages
t.c
Go to the documentation of this file.
1 #include <arpa/inet.h>
2 #include <stdio.h>
3 #include <stdint.h>
4 
5 struct addr_t {
6  union {
7  uint8_t u8[16];
8  uint16_t u16[8];
9  } addr;
10 };
11 
12 const unsigned char hex[] = "0123456789ABCDEF";
13 
14 size_t
15 print_addr(struct addr_t *addr, char *buf, size_t len) {
16  int i;
17  char *p = buf;
18  *p++ = '[';
19 
20  for (i=0; i < 16; i += 2) {
21  if (i) {
22  *p++ = ':';
23  }
24  *p++ = hex[(addr->addr.u8[i] & 0xf0) >> 4];
25  *p++ = hex[addr->addr.u8[i] & 0x0f];
26  *p++ = hex[(addr->addr.u8[i+1] & 0xf0) >> 4];
27  *p++ = hex[addr->addr.u8[i+1] & 0x0f];
28  }
29 
30  *p++ = ']';
31 
32  if (buf + len - p < 6)
33  return 0;
34 
35  p += snprintf((char *)p, buf + len - p + 1, ":%d", 50000);
36 
37  return p - buf;
38 }
39 
40 int main() {
41  struct addr_t addr;
42  char buf[100];
43  size_t result;
44 
45  addr.addr.u16[0] = htons(0x0011);
46  addr.addr.u16[1] = htons(0x2233);
47  addr.addr.u16[2] = htons(0x4455);
48  addr.addr.u16[3] = htons(0x6677);
49  addr.addr.u16[4] = htons(0x8899);
50  addr.addr.u16[5] = htons(0xaabb);
51  addr.addr.u16[6] = htons(0xccdd);
52  addr.addr.u16[7] = htons(0xeeff);
53 
54  result = print_addr(&addr, buf, 48);
55  buf[result] = '\0';
56 
57  printf("%s\n", buf);
58  return 0;
59 }