I have an embedded Linux system which is setup to use DHCP for eth0, but also has a link-local IP address configured as a fallback (eth0:1) just in case no IP address was obtained from DHCP.Is there a simple way to check, from a shell script, which IP address is in use?The closest I've got is this:$ ip route get 11.0.0.0 via 192.168.0.100 dev eth0  src 192.168.0.133    cache$ ifconfig eth0 0.0.0.0   # Simulate no IP obtained from DHCP$ ip route get 1                                                       1.0.0.0 via 192.168.0.100 dev eth0  src 169.254.197.131       cacheThis correctly identifies the IP address in use ('src' field). However this only works if a default gateway is configured, which will not be the case if DHCP was not available for some reason.How can I find out which IP address is in use even if no default gateway is configured ?
Two IP addresses on the same interface, find out which one is in use
linux;shell script;networking
The command ip route get ADDRESS does work even if no default gateway is configured. For example, if the following addresses are configured on eth0: 10.0.7.139/24, 169.254.1.2/16, and the default route is deleted, then$ ip route get 10.0.7.22210.0.7.222 dev eth0 src 10.0.7.139     cache$ ip route get 169.254.55169.254.55.0 dev eth0 src 169.254.1.2     cache$ ip route get 1RTNETLINK answers: Network is unreachableThe last answer is correct: there is no way to reach a host with any of the addresses 1.x.x.x, if no route to it exists. It is not the ip route get command that is not working, it is the network configuration that is wrong.Note that link-local means just that, an address that is intended to be used only on the the Ethernet link eth0 is connected to. It is not supposed to be used on an outgoing connection.Edit: clarifying comment added below.The routing table, and only the routing table, is what determines how a packet starts its journey to its destination. A route is always involved when sending an IP packet, even if the destination is on the local link or even the local host. Routing table entries also contain a source address, and this address of the matching route is chosen as the source IP address of the transmitted packet.There may be several ip addresses assigned to the same interface, even from the same address range, but only one of them (the primary address) is listed in the matching routing table entry.Thus ip route get (or indirectly ip route) gives the definitive answer to your question. From the ip-route man page: this command gets a single route to a destination and prints its contents exactly as the kernel sees it.