Improve IPv4 source address selection for multi-subnet interfaces #1074
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Improve IPv4 source address selection for multi-subnet interfaces
Problem
When an interface has multiple IPv4 addresses in different subnets, the current implementation always returns the first IPv4 address as the source address, regardless of the destination. This causes issues in multi-homed configurations where the interface serves multiple networks.
I encountered this issue with a setup where I registered an interface like this:
When a smoltcp socket attempts to send a packet to a device on the
172.24.24.0/24network, the initial ARP packets that were sent were being sent with the wrong source IP (172.18.1.2instead of172.24.24.14). This caused the remote device to ignore the ARP requests since they appeared to come from a different network, causing the packet to never be sent.Solution
This PR enhances the IPv4 source address selection algorithm to be subnet-aware. The new implementation:
Changes
get_source_address_ipv4()insrc/iface/interface/ipv4.rsto iterate through all interface addresses and check if they're in the same subnet as the destinationNow when communicating with a device at
172.24.24.100, the source address will correctly be172.24.24.14instead of172.18.1.2.