Jeff
Jeff

Reputation: 303

Android Unable to resolve host "<URL>" No address associated with host name

I have the following code to get IP address for certain url.

URL url = null;
String ip = null;

try {
    url = new URL("https://stackoverflow.com/");

    System.out.println(url.getHost());
    InetAddress address = InetAddress.getByName(url.getHost()); //<<< "Unable to resolve host..."
    ip = address.getHostAddress();
} 
catch (Exception e) {
    e.printStackTrace();
}

I have also added INTERNET permission in AndroidManifest.xml file. Below are the tests I have gone through:

Test #1: both wifi and mobile data turned on and internet access for wifi was disabled purposely.

Result: Unable to resolve host...

Test #2: turn off wifi and leave mobile data turned on.

Result: I was able to get the IP address as expected.

To my surprise, test results show that resolving url does not make use of mobile data with internet access, it will always work with wifi first if it's turned on.

My question is, how do I make sure that the code is always running with the network with internet access?

Upvotes: 1

Views: 1160

Answers (0)

Related Questions