Skip to content
Permalink
Browse files

net: sntp: Add convenience API for one-shot SNTP query

sntp_simple() function queries the server (passed as "addr[:port]"
string). It wraps calls to a number of other functions, and may be
useful to write simple, concise apps needing the absolute time.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
  • Loading branch information...
pfalcon authored and jukkar committed Apr 22, 2019
1 parent 426f3fa commit 22f1a29185bbf6b2547103967c8e725cdb51ffa6
Showing with 62 additions and 0 deletions.
  1. +16 −0 include/net/sntp.h
  2. +1 −0 subsys/net/lib/sntp/CMakeLists.txt
  3. +45 −0 subsys/net/lib/sntp/sntp_simple.c
@@ -82,6 +82,22 @@ int sntp_query(struct sntp_ctx *ctx, u32_t timeout,
*/
void sntp_close(struct sntp_ctx *ctx);

/**
* @brief Convenience function to query SNTP in one-shot fashion
*
* Convenience wrapper which calls getaddrinfo(), sntp_init(),
* sntp_query(), and sntp_close().
*
* @param server Address of server in format addr[:port]
* @param timeout Query timeout
* @param time Timestamp including integer and fractional seconds since
* 1 Jan 1970 (output).
*
* @return 0 if ok, <0 if error (-ETIMEDOUT if timeout).
*/
int sntp_simple(const char *server, u32_t timeout,
struct sntp_time *time);

/**
* @}
*/
@@ -2,4 +2,5 @@

zephyr_sources(
sntp.c
sntp_simple.c
)
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2019 Linaro Limited
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <errno.h>

#include <net/sntp.h>
#include <net/socketutils.h>

int sntp_simple(const char *server, u32_t timeout, struct sntp_time *time)
{
int res;
static struct addrinfo hints;
struct addrinfo *addr;
struct sntp_ctx sntp_ctx;

hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = 0;
/* 123 is the standard SNTP port per RFC4330 */
res = net_getaddrinfo_addr_str(server, "123", &hints, &addr);

if (res < 0) {
/* Just in case, as namespace for getaddrinfo errors is
* different from errno errors.
*/
errno = EDOM;
return res;
}

res = sntp_init(&sntp_ctx, addr->ai_addr, addr->ai_addrlen);
if (res < 0) {
goto freeaddr;
}

res = sntp_query(&sntp_ctx, timeout, time);

sntp_close(&sntp_ctx);

freeaddr:
freeaddrinfo(addr);

return res;
}

0 comments on commit 22f1a29

Please sign in to comment.
You can’t perform that action at this time.