0

I'm making an app with NativeScript and I need to get the local IP Adress of the device. I read in another page that you can access native API's, and they did this:

var app = require("application");
var context = android.content.Context;
var wifiManager = app.android.context.getSystemService(context.WIFI_SERVICE);
var wInfo = wifiManager.getConnectionInfo();
var ip = wInfo.getIpAddress();

I just started with NativeScript so I barely understand what that means.

In the code above, the IP is 251701440, and that's neither the local ip nor the public ip.

Is there any way to get the local IP of the device?

JCAguilera
  • 944
  • 1
  • 13
  • 32

1 Answers1

0

To get the IP address for Android devices, you could firstly verify the connection type. If it is WiFi, you could use android WiFiManager and in those cases when using mobile data connection - java.net.NetworkInterface.

WiFiManager

var context = app.android.context;
var  wifiMgr = context.getSystemService("wifi");
var wifiInfo = wifiMgr.getConnectionInfo();
var ip = wifiInfo.getIpAddress();
var  ipAddress = android.text.format.Formatter.formatIpAddress(ip);
console.log("ip");
console.log(ipAddress);

NetworkInterface

var en = java.net.NetworkInterface.getNetworkInterfaces();
                 console.log("NetworkInterface");
                 console.log(en)
                 for(var obj in en){
                     var intf = en.nextElement();
                     var enumIpAddr = intf.getInetAddresses();
                     console.log("enumIpAddr");
                     for(var obj2 in enumIpAddr){
                         console.log("obj");
                         if(enumIpAddr.hasMoreElements()){
                             var inetAddress = enumIpAddr.nextElement();
                             if ((!inetAddress.isLoopbackAddress()) && (inetAddress instanceof   java.net.Inet4Address)) {
                                     console.log("return inetAddress.getHostAddress(): "+inetAddress.getHostAddress());
                             }
                         }
                     }
                 }

The second approach with NetworkInterface is not fully tested and could have some issue with the returning the address.

Nikolay Tsonev
  • 1,919
  • 3
  • 16
  • 29