简体   繁体   中英

Connect to host name instead of IP address in android app

I am building an android app that connects to a backend service on my laptop. It connects to a localhost address where it gets data from JSON.

It works properly when I write the IP address of my laptop in my code. This IP address can change so I would like to use the host name which doesn't seem to work.

private static final String URLLocalhost = "http://localhost:8081/" ; // doesn't work
private static final String URLPCName = "http://PCNAME:8081/" ; // doesn't work
private static final String URLIPAddress = "http://192.168.xy:8081/" ; // works but IP needs to be modified

 @Override public List<Spike> getSpikes() { RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(URLPCName).build();

I get multiple ECONNREFUSED errors when it doesn't work.
It won't go public anytime soon so I don't have an URL for that.

I have found some solutions for this but they require making changes to my device. (haven't tried them)

  • Change DNS settings
  • Edit the hosts file

I would like any device (may be limited to the local wifi) to access this service without having to change settings in the device.

How can I connect using the host name from my code?


Related question, does not solve my question: How to connect my android app to the remote web server

Yes, AIUI, this is as expected. localhost refers to the adapter that the Android device is using, so will route requests to the phone itself (and thus fail).

The raw IP works fine, as it's unambiguous across the devices.

http://PCNAME:8081/ depends a bit on what kind of name PCNAME is here, and what your laptop is running. If that's a Windows machine name (using WINS ) then that won't work from Android / Linux by default anyway. Switching to the FQDN, eg PCNAME.subdomain.mydomain.org should probably work, but this relies on your DHCP router (or manual network setup in Android which you want to avoid) to search for that domain when unspecified, and Android respecting that routing for wireless, which I've found it doesn't (possibly this Android bug ).

Probably easier to have this passed a build parameter, or have config files for debug and production settings in your build. Another simple workaround is just to reserve a static IP for your laptop using DHCP reservation or just manually specifying an IP.

I have same issue. Did you have resolution for it. It seems that android is not connecting to network by server hostname, but can connect by direct IP address.

Kindly advise if you could manage . Thanks..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM