Skip to content

Commit

Permalink
Add support for tvOS and add getSubnet() (#94)
Browse files Browse the repository at this point in the history
* Add support for tvOS

* Add checks to build certain functions for only iOS

* Add getSubnet()

* Fix comma; Change type def

* Update to return subnet as a string instead of array

* Fix missing import for Android

Co-Authored-By: Chris <[email protected]>
  • Loading branch information
2 people authored and pusherman committed Jun 21, 2019
1 parent dd9753c commit f9617da
Show file tree
Hide file tree
Showing 6 changed files with 287 additions and 55 deletions.
3 changes: 2 additions & 1 deletion NetworkInfo.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ export namespace NetworkInfo {
function getBroadcast(): Promise<string | null>;
function getIPAddress(): Promise<string | null>;
function getIPV4Address(): Promise<string | null>;
}
function getSubnet(): Promise<string | null>;
}
8 changes: 6 additions & 2 deletions NetworkInfo.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';
"use strict";

import { NativeModules } from 'react-native';
import { NativeModules } from "react-native";
const { RNNetworkInfo } = NativeModules;

const NetworkInfo = {
Expand All @@ -22,6 +22,10 @@ const NetworkInfo = {

async getIPV4Address() {
return await RNNetworkInfo.getIPV4Address();
},

async getSubnet() {
return await RNNetworkInfo.getSubnet();
}
};

Expand Down
92 changes: 49 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Version 2+ requires RN 0.40 - RN 0.46
```javascript
npm install react-native-network-info --save
```

or

```javascript
Expand All @@ -25,25 +26,26 @@ yarn add react-native-network-info
## Usage

```javascript

import { NetworkInfo } from 'react-native-network-info';
import { NetworkInfo } from "react-native-network-info";

// Get Local IP
const ipAddress = await NetworkInfo.getIPAddress();

// Get IPv4 IP
const ipv4Address = await NetworkInfo.getIPV4Address()
const ipv4Address = await NetworkInfo.getIPV4Address();

// Get Broadcast
const broadcast = await NetworkInfo.getBroadcast()
const broadcast = await NetworkInfo.getBroadcast();

// Get SSID
const ssid = await NetworkInfo.getSSID()
const ssid = await NetworkInfo.getSSID();

// Get BSSID
const bssid = await NetworkInfo.getBSSID()
```
const bssid = await NetworkInfo.getBSSID();

// Get Subnet
const subnet = await NetworkInfo.getSubnet();
```

### Manually Linking the Library

Expand All @@ -62,51 +64,55 @@ Run your project (Cmd+R)
### `Android`

1. Add the following lines to `android/settings.gradle`:
```gradle
include ':react-native-network-info'
project(':react-native-network-info').projectDir = new File(settingsDir, '../node_modules/react-native-network-info/android')
```

```gradle
include ':react-native-network-info'
project(':react-native-network-info').projectDir = new File(settingsDir, '../node_modules/react-native-network-info/android')
```

2. Update the android build tools version to `2.2.+` in `android/build.gradle`:
```gradle
buildscript {
...
dependencies {
classpath 'com.android.tools.build:gradle:2.2.+' // <- USE 2.2.+ version
}
...
}
...
```
```gradle
buildscript {
...
dependencies {
classpath 'com.android.tools.build:gradle:2.2.+' // <- USE 2.2.+ version
}
...
}
...
```
3. Update the gradle version to `2.14.1` in `android/gradle/wrapper/gradle-wrapper.properties`:
```
...
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
```

```
...
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
```

4. Add the compile line to the dependencies in `android/app/build.gradle`:
```gradle
dependencies {
...
compile project(':react-native-network-info')
}
```

```gradle
dependencies {
...
compile project(':react-native-network-info')
}
```

5. Add the import and link the package in `MainApplication.java`:
```java
import com.pusherman.networkinfo.RNNetworkInfoPackage; // <-- add this import

public class MainApplication extends Application implements ReactApplication {
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNNetworkInfoPackage() // <-- add this line
);
}
}
```
```java
import com.pusherman.networkinfo.RNNetworkInfoPackage; // <-- add this import

public class MainApplication extends Application implements ReactApplication {
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNNetworkInfoPackage() // <-- add this line
);
}
}
```

## Dev Notes

Notes on how this package was made can be [found here](https://eastcodes.com/packaging-and-sharing-react-native-modules "Packaging and Sharing React Native Modules").
66 changes: 57 additions & 9 deletions android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,20 @@
import java.util.Enumeration;
import java.util.Arrays;
import java.util.List;

import java.net.Inet6Address;

public class RNNetworkInfo extends ReactContextBaseJavaModule {
WifiManager wifi;

public static final String TAG = "RNNetworkInfo";

public static List<String> DSLITE_LIST = Arrays.asList("192.0.0.0", "192.0.0.1", "192.0.0.2", "192.0.0.3", "192.0.0.4", "192.0.0.5", "192.0.0.6", "192.0.0.7");

public static List<String> DSLITE_LIST = Arrays.asList("192.0.0.0", "192.0.0.1", "192.0.0.2", "192.0.0.3",
"192.0.0.4", "192.0.0.5", "192.0.0.6", "192.0.0.7");

public RNNetworkInfo(ReactApplicationContext reactContext) {
super(reactContext);

wifi = (WifiManager) reactContext.getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
wifi = (WifiManager) reactContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
}

@Override
Expand Down Expand Up @@ -96,7 +95,8 @@ public void run() {
String ipAddress = null;

for (InterfaceAddress address : getInetAddresses()) {
if (!address.getAddress().isLoopbackAddress()/*address.getAddress().toString().equalsIgnoreCase(ip)*/) {
if (!address.getAddress()
.isLoopbackAddress()/* address.getAddress().toString().equalsIgnoreCase(ip) */) {
ipAddress = address.getBroadcast().toString();
}
}
Expand Down Expand Up @@ -160,19 +160,67 @@ public void run() {
}).start();
}

@ReactMethod
public void getSubnet(final Promise promise) throws Exception {
new Thread(new Runnable() {
public void run() {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
if (iface.isLoopback() || !iface.isUp())
continue;

Enumeration<InetAddress> addresses = iface.getInetAddresses();
for (InterfaceAddress address : iface.getInterfaceAddresses()) {

InetAddress addr = addresses.nextElement();
if (addr instanceof Inet6Address)
continue;

promise.resolve(intToIP(address.getNetworkPrefixLength()));
return;
}
}
} catch (Exception e) {
promise.resolve("0.0.0.0");
}
}
}).start();
}

private String intToIP(int ip) {
String[] finl = { "", "", "", "" };
int k = 1;

for (int i = 0; i < 4; i++) {
for (int j = 0; j < 8; j++) {
if (k <= ip) {
finl[i] += "1";
} else {
finl[i] += "0";
}
k++;

}
}
return Integer.parseInt(finl[0], 2) + "." + Integer.parseInt(finl[1], 2) + "." + Integer.parseInt(finl[2], 2)
+ "." + Integer.parseInt(finl[3], 2);
}

private Boolean inDSLITERange(String ip) {
// Fixes issue https://github.com/pusherman/react-native-network-info/issues/43
// Based on comment https://github.com/pusherman/react-native-network-info/issues/43#issuecomment-358360692
// Based on comment
// https://github.com/pusherman/react-native-network-info/issues/43#issuecomment-358360692
// added this check in getIPAddress and getIPV4Address
return RNNetworkInfo.DSLITE_LIST.contains(ip);
}


private List<InterfaceAddress> getInetAddresses() {
List<InterfaceAddress> addresses = new ArrayList<>();
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();

for (InterfaceAddress interface_address : intf.getInterfaceAddresses()) {
Expand Down
46 changes: 46 additions & 0 deletions ios/RNNetworkInfo.m
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
#import <ifaddrs.h>
#import <arpa/inet.h>
#include <net/if.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <TargetConditionals.h>

#define IOS_CELLULAR @"pdp_ip0"
#define IOS_WIFI @"en0"
Expand All @@ -24,6 +27,7 @@ @implementation RNNetworkInfo

RCT_EXPORT_MODULE();

#if TARGET_OS_IOS
RCT_EXPORT_METHOD(getSSID:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
Expand All @@ -46,7 +50,9 @@ @implementation RNNetworkInfo
resolve(NULL);
}
}
#endif

#if TARGET_OS_IOS
RCT_EXPORT_METHOD(getBSSID:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
Expand All @@ -68,6 +74,7 @@ @implementation RNNetworkInfo
resolve(NULL);
}
}
#endif

RCT_EXPORT_METHOD(getBroadcast:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
Expand Down Expand Up @@ -162,6 +169,45 @@ @implementation RNNetworkInfo
}
}

RCT_EXPORT_METHOD(getSubnet:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
@try {
NSString *netmask = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;

int success = 0;

// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0)
{
temp_addr = interfaces;

while(temp_addr != NULL)
{
// check if interface is en0 which is the wifi connection on the iPhone
if(temp_addr->ifa_addr->sa_family == AF_INET)
{
if([@(temp_addr->ifa_name) isEqualToString:@"en0"])
{
netmask = @(inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr));
}
}

temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);

NSString *addressToReturn = netmask ? netmask : @"0.0.0.0";
resolve(addressToReturn);
} @catch (NSException *exception) {
resolve(NULL);
}
}

- (NSDictionary *)getAllIPAddresses
{
NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
Expand Down
Loading

0 comments on commit f9617da

Please sign in to comment.