Commit 22f1a291 authored by Paul Sokolovsky's avatar Paul Sokolovsky Committed by Jukka Rissanen
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: default avatarPaul Sokolovsky <paul.sokolovsky@linaro.org>
parent 426f3fa1
Loading
Loading
Loading
Loading
+16 −0
Original line number Diff line number Diff line
@@ -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);

/**
 * @}
 */
+1 −0
Original line number Diff line number Diff line
@@ -2,4 +2,5 @@

zephyr_sources(
  sntp.c
  sntp_simple.c
)
+45 −0
Original line number Diff line number Diff line
/*
 * 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;
}