From a5b61409a5b0c5bb21bc0e926ce106cccfd94b83 Mon Sep 17 00:00:00 2001 From: Olaf Bergmann Date: Tue, 27 Oct 2015 13:05:03 +0100 Subject: [PATCH] coap_io.c: set local address after bind for new endpoint This fixes a bug reported by Daniel Petrie: "When the coap-client is used and a local address to bind to is specified, but the local port is not specified, I get errors for the response coming in from an unexpected interface and the response is dropped/ignored." The solution here is to call getsockname() after successful bind() in coap_new_endpoint() to set ep->addr to the actual transport address being used. --- src/coap_io.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/coap_io.c b/src/coap_io.c index 057462f5..cbf2263d 100644 --- a/src/coap_io.c +++ b/src/coap_io.c @@ -165,8 +165,14 @@ coap_new_endpoint(const coap_address_t *addr, int flags) { memset(ep, 0, sizeof(struct coap_endpoint_t)); ep->handle.fd = sockfd; ep->flags = flags; - memcpy(&ep->addr, addr, sizeof(coap_address_t)); - + + ep->addr.size = addr->size; + if (getsockname(sockfd, &ep->addr.addr.sa, &ep->addr.size) < 0) { + coap_log(LOG_WARNING, "coap_new_endpoint: cannot determine local address"); + close (sockfd); + return NULL; + } + #ifndef NDEBUG if (LOG_DEBUG <= coap_get_log_level()) { #ifndef INET6_ADDRSTRLEN @@ -174,7 +180,7 @@ coap_new_endpoint(const coap_address_t *addr, int flags) { #endif unsigned char addr_str[INET6_ADDRSTRLEN+8]; - if (coap_print_addr(addr, addr_str, INET6_ADDRSTRLEN+8)) { + if (coap_print_addr(&ep->addr, addr_str, INET6_ADDRSTRLEN+8)) { debug("created %sendpoint %s\n", ep->flags & COAP_ENDPOINT_DTLS ? "DTLS " : "", addr_str);