开发者

Android: Using resolved IP Address instead of hostname

开发者 https://www.devze.com 2023-03-13 19:45 出处:网络
I would want to use resolved IP address to connect to server instead of hos开发者_运维技巧tname. Here is my code snippets:

I would want to use resolved IP address to connect to server instead of hos开发者_运维技巧tname. 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号