Question

I would want to use resolved IP address to connect to server instead of hostname. Here is my code snippets:

     // Get domain name from URL
    String domainName = url.substring("http://".length(),
            url.indexOf("/", 8));
    // Get IP address as string
    InetAddress inet = null;
    try {
        inet = InetAddress.getByName(domainName);
    } catch (UnknownHostException e) {
        Log.i(TAG, "The IP address cannot be resolved for " + domainName);
    }
        resolvedIP = inet.getHostAddress(); 

Here i'm able to successfully get IP ADDRESS. Now i try to replace my url as below:

url = url.replace(domainName, resolvedIP);

Now I connect to server:
URL download = new URL(url);


conn = (HttpURLConnection) url.openConnection();

conn.getInputStream(); //Throws IO Exception

I'm able to successfully connect if I use URL as it is (without replacing domain name with IP Address).

Please let me know if I'm doing things correctly.

Was it helpful?

Solution

As a general rule, try to use the hostname-based URL. It is not uncommon to have multiple web sites on the same IP, distinguished only by the site name (so-called virtual hosting). What you are doing will only work for the case where there is a single site on a given IP.

It's quite common for load-balancers to have one IP for each "site" it balances, but there's still no guarantee that you will connect to the same backend for two consecutive requests. However, there are web load balancers that extend the use of virtual hosting all the way to the load-balancing layer.

I would simply try to stick downloading by a hostname-based URL.

OTHER TIPS

One solution to get around the VHost problem is to use your own DNS server and always return the same ip address for the host you're connecting to.

This requires no change to your application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top