NativeScript - Get device local IP address

Viewed 1009

I'd like to get the local IP address of my device using NativeScript / JavaScript.

I have done a search and found a way to do that on Android, but I'd like to have a cross-platform solution that works also on iOS.

I'm currently using NSPlayground on an iPhone 6S running iOS 11.4.

1 Answers

If you don't find a plugin to do that easily, you will have to access the native platform-specific APIs to do it on each platform yourself.

On Android, you would do something like this:

import * as application from 'application';

...

const wifiService: any = application.android.context
    .getSystemService(android.content.Context.WIFI_SERVICE);

// See https://developer.android.com/reference/android/net/wifi/WifiManager#getConnectionInfo()
const wifiInfo: any = wifiService.getConnectionInfo();

// See https://developer.android.com/reference/android/net/wifi/WifiInfo.html#getIpAddress()
const ip: number = wifiInfo.getIpAddress();

Note the IP returned by WifiInfo#getIpAddress is a number in TypeScript (int in Java), which means that you need a way to convert it to convert it to the CIDR notation:

function intToCDIRIP(ip) {
   return `${ (ip >> 24 ) & 0xFF }.${ (ip >> 16 ) & 0xFF }.${ (ip >> 8 ) & 0xFF }.${ ip & 0xFF }`;
}

console.log(intToCDIRIP(33353454354)); // Should be 196.5.83.18

You would then need to do something similar on iOS. Here you have another question & answer explaining how you would do that on iOS using Swift, which you would have to translate to TypeScript/JavaScript to be able to get the IP on both platforms: Swift - Get device's IP Address

Actually, you could consider creating a plugin that does that and sharing it with the community

Related