Skip to content

Commit 391290e

Browse files
Damian-Nordickartben
authored andcommitted
net: shell: udp: allow sending packet when bound
"udp bind" and "udp send" commands use the same net context variable and they fail early if the context is already used. This prevents from using "udp send" after "udp bind", which makes the commands hard to use for testing bidirectional communication. Make "udp send" reuse the already bound context if possible, and resort to allocating temporary one otherwise. Signed-off-by: Damian Krolik <damian.krolik@nordicsemi.no>
1 parent 81141b1 commit 391290e

File tree

1 file changed

+15
-14
lines changed
  • subsys/net/lib/shell

1 file changed

+15
-14
lines changed

subsys/net/lib/shell/udp.c

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ static int cmd_net_udp_bind(const struct shell *sh, size_t argc, char *argv[])
8282
return -EINVAL;
8383
}
8484

85-
if (udp_ctx && net_context_is_used(udp_ctx)) {
85+
if (udp_ctx != NULL && net_context_is_used(udp_ctx)) {
8686
PR_WARNING("Network context already in use\n");
8787
return -EALREADY;
8888
}
@@ -191,6 +191,7 @@ static int cmd_net_udp_send(const struct shell *sh, size_t argc, char *argv[])
191191
uint16_t port;
192192
uint8_t *payload = NULL;
193193
int ret;
194+
bool should_release_ctx = false;
194195

195196
struct net_if *iface;
196197
struct sockaddr addr;
@@ -210,23 +211,21 @@ static int cmd_net_udp_send(const struct shell *sh, size_t argc, char *argv[])
210211
return -EINVAL;
211212
}
212213

213-
if (udp_ctx && net_context_is_used(udp_ctx)) {
214-
PR_WARNING("Network context already in use\n");
215-
return -EALREADY;
216-
}
217-
218214
memset(&addr, 0, sizeof(addr));
219215
ret = net_ipaddr_parse(host, strlen(host), &addr);
220216
if (ret < 0) {
221217
PR_WARNING("Cannot parse address \"%s\"\n", host);
222218
return ret;
223219
}
224220

225-
ret = net_context_get(addr.sa_family, SOCK_DGRAM, IPPROTO_UDP,
226-
&udp_ctx);
227-
if (ret < 0) {
228-
PR_WARNING("Cannot get UDP context (%d)\n", ret);
229-
return ret;
221+
/* Re-use already bound context if possible, or allocate temporary one. */
222+
if (udp_ctx == NULL || !net_context_is_used(udp_ctx)) {
223+
ret = net_context_get(addr.sa_family, SOCK_DGRAM, IPPROTO_UDP, &udp_ctx);
224+
if (ret < 0) {
225+
PR_WARNING("Cannot get UDP context (%d)\n", ret);
226+
return ret;
227+
}
228+
should_release_ctx = true;
230229
}
231230

232231
udp_shell = sh;
@@ -274,9 +273,11 @@ static int cmd_net_udp_send(const struct shell *sh, size_t argc, char *argv[])
274273
}
275274

276275
release_ctx:
277-
ret = net_context_put(udp_ctx);
278-
if (ret < 0) {
279-
PR_WARNING("Cannot put UDP context (%d)\n", ret);
276+
if (should_release_ctx) {
277+
ret = net_context_put(udp_ctx);
278+
if (ret < 0) {
279+
PR_WARNING("Cannot put UDP context (%d)\n", ret);
280+
}
280281
}
281282

282283
return 0;

0 commit comments

Comments
 (0)