From dbe46353689d3469dce0ebd60602233701639b33 Mon Sep 17 00:00:00 2001 From: Michael Scott Date: Mon, 23 Jan 2017 13:42:06 -0800 Subject: [PATCH] samples: net: irc_bot: add helper function in_addr_set() The aim of this helper function is to remove duplicate code for setting the parameters of in_addr structures. Change-Id: Id882a5947c47a9b6f92924ce8fb04023540fbb8d Signed-off-by: Michael Scott --- samples/net/irc_bot/src/irc-bot.c | 37 +++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/samples/net/irc_bot/src/irc-bot.c b/samples/net/irc_bot/src/irc-bot.c index 7d01b1c5d02..7392ebf94b6 100644 --- a/samples/net/irc_bot/src/irc-bot.c +++ b/samples/net/irc_bot/src/irc-bot.c @@ -266,6 +266,43 @@ on_context_recv(struct net_context *ctx, struct net_buf *buf, } } +static int in_addr_set(sa_family_t family, + const char *ip_addr, + int port, + struct sockaddr *_sockaddr) +{ + int rc = 0; + + _sockaddr->family = family; + + if (ip_addr) { + if (family == AF_INET6) { + rc = net_addr_pton(family, + ip_addr, + &net_sin6(_sockaddr)->sin6_addr); + } else { + rc = net_addr_pton(family, + ip_addr, + &net_sin(_sockaddr)->sin_addr); + } + + if (rc < 0) { + NET_ERR("Invalid IP address: %s", ip_addr); + return -EINVAL; + } + } + + if (port >= 0) { + if (family == AF_INET6) { + net_sin6(_sockaddr)->sin6_port = htons(port); + } else { + net_sin(_sockaddr)->sin_port = htons(port); + } + } + + return rc; +} + static void on_context_connect(struct net_context *ctx, void *data) {