How to get local IP-address of android-device

moster67

Expert
Licensed User
Longtime User
My app connects to a server running normally in the user's own home-network (LAN) but by using a Dynamic DNS-address (and portforwarding), the app can reach the server also remotely (for instance over 3G or using a WIFI hotspot).

So my app has two user-settings:
Server LAN IP-address: 192.168.1.8
Dynamic DNS: myIP.mydns.com

I now want my app to read the IP-address which the Android-device has been assigned and based upon it, it should compare the ip-address obtained against the two settings mentioned above. If the ip-address obtained has the same 3 initials parts of the Server LAN IP-address, then my app knows that it needs to connect to the server using Server LAN IP-address (for instance: obtained IP-address is: 192.168.1.15 and reading this, my app can say it is part of the same network since the 3 first parts are identical to Server LAN IP-address being 192.168.1.8.)

On the other hand, if the obtained ip-address does not follow the same pattern i.e. the first 3 parts of the ip-address obtained is different from the Server LAN IP-address, then my app should use Dynamic DNS.

Also, I believe if there is no active connection on the device (WIFI, 3G-data is off), the Android-device should return localhost i.e. 127.0.0.1. Is this correct?

I hope this makes sense :) Basically I want my app to auto-detect which setting to use when connecting to the server but to do this I need to know the ip-address which has been assigned to the android-device.

Edit: I guess I could also ping the Server LAN IP-address and if I get a reply, then I know I need to use Server LAN IP-address - if I don't get a reply, I need to use Dynamic DNS. But using ping would perhaps require a rooted device so I am more reluctant to this solution.

Thanks!
 
Last edited:
Top