Java.net.unknownhostexception: Invalid hostname for server: local
⚡TLDR
The error java.net.UnknownHostException: Invalid hostname for server: local
is hinting that "local" doesn't register as a valid server name. Swap "local" with "localhost" or "127.0.0.1" to address your own machine.
Troubleshooting the issue
Inspecting hostname resolution
To see if "local" corresponds to an IP:
ping local
command in terminal.- No party called "local"? Then it's not resolvable.
- Add
127.0.0.1 local
to/etc/hosts
if "local" is a deliberately set hostname.
Addressing localhost server and testing cases
In cases with Android emulators or local server testing do the below:
- Make sure to use "localhost" or "127.0.0.1" for emulator loopback.
- Add virtual hostname to emulator configurations as necessary.
Code refining
In code, where a hostname gets set programmatically:
- Humorously, even code can trim! Add
String.trim()
, it removes pesky whitespaces. - Use
::1
for loopback address in IPv6 setup, it like hipster version of 127.0.0.1. - Make sure the semicolon separated host strings are correctly parsed.
Gracefully handling the exception
UnknownHostException
is an uninvited guest, make ready with:
A humble notice to the user is helpful when things go south!
Checking available network access
- Ensure your machine has a valid internet connection or Wi-Fi.
- Ping the hostname and ponder the DNS settings if "local" should be resolved.
Dealing with the UnknownHostException
When UnknownHostException
makes an unwanted appearance:
- The given hostname might have no DNS entry or host file entry.
- You are trying to connect to a non-existent server like
google.com
where party just ended!
Addressing emulator-specific issues
Make sure the hostname is communicated well within the emulator:
- Make the required changes to the
/etc/hosts
file of the emulator. - Thoroughly check the network access point or router configurations.
If the issue persists
If the issue remains unchanged, consider:
- Use command
hostname -f
for full hostname resolution. - Attempt connecting to local network if the server is on the same network.
- Probe deeper. Just like a party,
UnknownHostException
can have multiple reasons!
Linked
Was this article helpful?