From aa8dfe10bd0489a64c8d5c9f6d98c4f9d6ba4dce Mon Sep 17 00:00:00 2001 From: Abtin Keshavarzian Date: Wed, 7 Feb 2024 10:38:57 -0800 Subject: [PATCH] [ip6] simplify `Ip6::SelectSourceAddress()` (#9832) This commit simplifies `Ip6::SelectSourceAddress()` by adding a new boolean `newAddrIsPreferred` tracking whether the new address is preferred over the previously chosen one as we iterate over all addresses. --- src/core/net/ip6.cpp | 58 +++++++++++++------------------------------- 1 file changed, 17 insertions(+), 41 deletions(-) diff --git a/src/core/net/ip6.cpp b/src/core/net/ip6.cpp index 3637b9008..3a6472a3f 100644 --- a/src/core/net/ip6.cpp +++ b/src/core/net/ip6.cpp @@ -1309,6 +1309,7 @@ const Address *Ip6::SelectSourceAddress(const Address &aDestination) const for (const Netif::UnicastAddress &addr : Get().GetUnicastAddresses()) { + bool newAddrIsPreferred = false; uint8_t matchLen; uint8_t overrideScope; @@ -1339,71 +1340,46 @@ const Address *Ip6::SelectSourceAddress(const Address &aDestination) const if (bestAddr == nullptr) { - bestAddr = &addr; - bestMatchLen = matchLen; + newAddrIsPreferred = true; } else if (addr.GetScope() < bestAddr->GetScope()) { // Rule 2: Prefer appropriate scope - if (addr.GetScope() >= overrideScope) - { - bestAddr = &addr; - bestMatchLen = matchLen; - } - else - { - continue; - } + newAddrIsPreferred = (addr.GetScope() >= overrideScope); } else if (addr.GetScope() > bestAddr->GetScope()) { - if (bestAddr->GetScope() < overrideScope) - { - bestAddr = &addr; - bestMatchLen = matchLen; - } - else - { - continue; - } + newAddrIsPreferred = (bestAddr->GetScope() < overrideScope); } else if (addr.mPreferred != bestAddr->mPreferred) { // Rule 3: Avoid deprecated addresses - - if (addr.mPreferred) - { - bestAddr = &addr; - bestMatchLen = matchLen; - } - else - { - continue; - } + newAddrIsPreferred = addr.mPreferred; } else if (matchLen > bestMatchLen) { // Rule 6: Prefer matching label // Rule 7: Prefer public address // Rule 8: Use longest prefix matching - bestAddr = &addr; - bestMatchLen = matchLen; + + newAddrIsPreferred = true; } else if ((matchLen == bestMatchLen) && (destIsRloc == Get().IsRoutingLocator(addr.GetAddress()))) { // Additional rule: Prefer RLOC source for RLOC destination, EID source for anything else - bestAddr = &addr; - bestMatchLen = matchLen; - } - else - { - continue; + newAddrIsPreferred = true; } - // infer destination scope based on prefix match - if (bestMatchLen >= bestAddr->mPrefixLength) + if (newAddrIsPreferred) { - destScope = bestAddr->GetScope(); + bestAddr = &addr; + bestMatchLen = matchLen; + + // Infer destination scope based on prefix match + if (bestMatchLen >= bestAddr->mPrefixLength) + { + destScope = bestAddr->GetScope(); + } } }