1 /*
2 * Copyright (c) 2017 Linaro Limited
3 * Copyright (c) 2019 Intel Corporation
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8 #include <zephyr/logging/log.h>
9 LOG_MODULE_REGISTER(net_sntp_client_sample, LOG_LEVEL_DBG);
10
11 #include <zephyr/net/sntp.h>
12 #include <arpa/inet.h>
13
14 #include "config.h"
15 #include "net_sample_common.h"
16
17 #define SNTP_PORT 123
18
main(void)19 int main(void)
20 {
21 struct sntp_ctx ctx;
22 struct sockaddr_in addr;
23 #if defined(CONFIG_NET_IPV6)
24 struct sockaddr_in6 addr6;
25 #endif
26 struct sntp_time sntp_time;
27 int rv;
28
29 wait_for_network();
30
31 /* ipv4 */
32 memset(&addr, 0, sizeof(addr));
33 addr.sin_family = AF_INET;
34 addr.sin_port = htons(SNTP_PORT);
35 inet_pton(AF_INET, SERVER_ADDR, &addr.sin_addr);
36
37 rv = sntp_init(&ctx, (struct sockaddr *) &addr,
38 sizeof(struct sockaddr_in));
39 if (rv < 0) {
40 LOG_ERR("Failed to init SNTP IPv4 ctx: %d", rv);
41 goto end;
42 }
43
44 LOG_INF("Sending SNTP IPv4 request...");
45 rv = sntp_query(&ctx, 4 * MSEC_PER_SEC, &sntp_time);
46 if (rv < 0) {
47 LOG_ERR("SNTP IPv4 request failed: %d", rv);
48 goto end;
49 }
50
51 LOG_INF("status: %d", rv);
52 LOG_INF("time since Epoch: high word: %u, low word: %u",
53 (uint32_t)(sntp_time.seconds >> 32), (uint32_t)sntp_time.seconds);
54
55 #if defined(CONFIG_NET_IPV6)
56 sntp_close(&ctx);
57
58 /* ipv6 */
59 memset(&addr6, 0, sizeof(addr6));
60 addr6.sin6_family = AF_INET6;
61 addr6.sin6_port = htons(SNTP_PORT);
62 inet_pton(AF_INET6, SERVER_ADDR6, &addr6.sin6_addr);
63
64 rv = sntp_init(&ctx, (struct sockaddr *) &addr6,
65 sizeof(struct sockaddr_in6));
66 if (rv < 0) {
67 LOG_ERR("Failed to init SNTP IPv6 ctx: %d", rv);
68 goto end;
69 }
70
71 LOG_INF("Sending SNTP IPv6 request...");
72 /* With such a timeout, this is expected to fail. */
73 rv = sntp_query(&ctx, 0, &sntp_time);
74 if (rv < 0) {
75 LOG_ERR("SNTP IPv6 request: %d", rv);
76 goto end;
77 }
78
79 LOG_INF("status: %d", rv);
80 LOG_INF("time since Epoch: high word: %u, low word: %u",
81 (uint32_t)(sntp_time.seconds >> 32), (uint32_t)sntp_time.seconds);
82 #endif
83
84 end:
85 sntp_close(&ctx);
86 return 0;
87 }
88