3

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.

Danziger
  • 19,628
  • 4
  • 53
  • 83

1 Answers1

3

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

Danziger
  • 19,628
  • 4
  • 53
  • 83
  • 1
    Thanks for the answer, at the moment i don't I think I have what is needed for such a work, I'd prefer to use a plugin, but it seems there is none – LukeTheWalker Sep 04 '18 at 20:04
  • 1
    @LukeTheWalker This looks like a great idea for a plugin. The community will be very grateful :) – anthares Sep 05 '18 at 13:35