This one should be pretty bulletproof. Use a single sed command to dump the list of all ip addresses from interfaces showing in ifconfig.
99% of the time you can just use the local address to talk to yourself. This is just an example to show you how wrangle the ip address using awk. Rewrite the hosts file so the host itself can use it’s external address by name. Write out the basic stuff in hosts that doesn’t change then write out the current IP address.
Here’s a bunch of ways to get the ip addresses for all your network interfaces using ifconfig.