From ea88a0da409592d25d8229a8b61420eb3755d9c3 Mon Sep 17 00:00:00 2001 From: Hossein Mohammadi Date: Mon, 25 Feb 2019 11:35:17 +0330 Subject: [PATCH 1/3] use async await instead of using the callback --- NetworkInfo.d.ts | 12 +- NetworkInfo.js | 28 +-- README.md | 20 +- .../pusherman/networkinfo/RNNetworkInfo.java | 165 ++++++++++------- ios/RNNetworkInfo.m | 175 ++++++++++-------- 5 files changed, 230 insertions(+), 170 deletions(-) diff --git a/NetworkInfo.d.ts b/NetworkInfo.d.ts index 25a8f52..214e88d 100644 --- a/NetworkInfo.d.ts +++ b/NetworkInfo.d.ts @@ -1,7 +1,7 @@ export namespace NetworkInfo { - function getSSID(callback: (ssid: string) => void): void; - function getBSSID(callback: (bssid: string | null) => void): void; - function getBroadcast(callback: (ip: string | null) => void): void; - function getIPAddress(callback: (ip: string | null) => void): void; - function getIPV4Address(callback: (ip: string | null) => void): void; -} + function getSSID(): Promise; + function getBSSID(): Promise; + function getBroadcast(): Promise; + function getIPAddress(): Promise; + function getIPV4Address(): Promise; +} \ No newline at end of file diff --git a/NetworkInfo.js b/NetworkInfo.js index b6cbc8b..edf825a 100644 --- a/NetworkInfo.js +++ b/NetworkInfo.js @@ -1,28 +1,28 @@ -'use strict'; +"use strict"; -import { NativeModules } from 'react-native'; +import { NativeModules } from "react-native"; const { RNNetworkInfo } = NativeModules; const NetworkInfo = { - getSSID(ssid) { - RNNetworkInfo.getSSID(ssid); + async getSSID() { + return await RNNetworkInfo.getSSID(); }, - getBSSID(bssid) { - RNNetworkInfo.getBSSID(bssid); + async getBSSID() { + return await RNNetworkInfo.getBSSID(); }, - getBroadcast(ip) { - RNNetworkInfo.getBroadcast(ip); + async getBroadcast() { + return await RNNetworkInfo.getBroadcast(); }, - getIPAddress(ip) { - RNNetworkInfo.getIPAddress(ip); + async getIPAddress() { + return await RNNetworkInfo.getIPAddress(); }, - getIPV4Address(ip) { - RNNetworkInfo.getIPV4Address(ip); + async getIPV4Address() { + return await RNNetworkInfo.getIPV4Address(); } -} +}; -module.exports = { NetworkInfo } +module.exports = { NetworkInfo }; diff --git a/README.md b/README.md index 779fa7b..ecd8f90 100644 --- a/README.md +++ b/README.md @@ -29,29 +29,19 @@ yarn add react-native-network-info import { NetworkInfo } from 'react-native-network-info'; // Get Local IP -NetworkInfo.getIPAddress(ip => { - console.log(ip); -}); +await NetworkInfo.getIPAddress(); // Get IPv4 IP -NetworkInfo.getIPV4Address(ipv4 => { - console.log(ipv4); -}); +await NetworkInfo.getIPV4Address() // Get Broadcast -NetworkInfo.getBroadcast(address => { - console.log(address); -}); +await NetworkInfo.getBroadcast() // Get SSID -NetworkInfo.getSSID(ssid => { - console.log(ssid); -}); +await NetworkInfo.getSSID() // Get BSSID -NetworkInfo.getBSSID(ssid => { - console.log(ssid); -}); +await NetworkInfo.getBSSID() ``` diff --git a/android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java b/android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java index 01c8bfc..ba62a1e 100644 --- a/android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java +++ b/android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java @@ -6,7 +6,7 @@ import android.support.annotation.NonNull; import android.net.wifi.SupplicantState; import android.util.Log; - +import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; @@ -45,80 +45,121 @@ public String getName() { } @ReactMethod - public void getSSID(final Callback callback) { - WifiInfo info = wifi.getConnectionInfo(); - - // This value should be wrapped in double quotes, so we need to unwrap it. - // https://stackoverflow.com/a/34848930/5732760 - String ssid = "error"; - if (info.getSupplicantState() == SupplicantState.COMPLETED) { - ssid = info.getSSID(); - if (ssid.startsWith("\"") && ssid.endsWith("\"")) { - ssid = ssid.substring(1, ssid.length() - 1); - } - } - - callback.invoke(ssid); + public void getSSID(final Promise promise) throws Exception { + new Thread(new Runnable() { + public void run() { + try { + WifiInfo info = wifi.getConnectionInfo(); + + // This value should be wrapped in double quotes, so we need to unwrap it. + // https://stackoverflow.com/a/34848930/5732760 + String ssid = null; + if (info.getSupplicantState() == SupplicantState.COMPLETED) { + ssid = info.getSSID(); + if (ssid.startsWith("\"") && ssid.endsWith("\"")) { + ssid = ssid.substring(1, ssid.length() - 1); + } + } + promise.resolve(ssid); + } catch (Exception e) { + promise.reject("error ", e); + } + + } + }).start(); } @ReactMethod - public void getBSSID(final Callback callback) { - WifiInfo info = wifi.getConnectionInfo(); - - // https://stackoverflow.com/a/34848930/5732760 - String bssid = "error"; - if (info.getSupplicantState() == SupplicantState.COMPLETED) { - bssid = wifi.getConnectionInfo().getBSSID(); - } - - callback.invoke(bssid); + public void getBSSID(final Promise promise) throws Exception { + new Thread(new Runnable() { + public void run() { + try { + WifiInfo info = wifi.getConnectionInfo(); + + // https://stackoverflow.com/a/34848930/5732760 + String bssid = null; + if (info.getSupplicantState() == SupplicantState.COMPLETED) { + bssid = wifi.getConnectionInfo().getBSSID(); + } + promise.resolve(bssid); + } catch (Exception e) { + promise.reject("error ", e); + } + + } + }).start(); } @ReactMethod - public void getBroadcast(/*@NonNull String ip, */final Callback callback) { - String ipAddress = "error"; - - for (InterfaceAddress address : getInetAddresses()) { - if (!address.getAddress().isLoopbackAddress()/*address.getAddress().toString().equalsIgnoreCase(ip)*/) { - ipAddress = address.getBroadcast().toString(); - } - } - - callback.invoke(ipAddress); + public void getBroadcast(final Promise promise) throws Exception { + new Thread(new Runnable() { + public void run() { + try { + String ipAddress = null; + + for (InterfaceAddress address : getInetAddresses()) { + if (!address.getAddress().isLoopbackAddress()/*address.getAddress().toString().equalsIgnoreCase(ip)*/) { + ipAddress = address.getBroadcast().toString(); + } + } + promise.resolve(ipAddress); + } catch (Exception e) { + promise.reject("error ", e); + } + + } + }).start(); } @ReactMethod - public void getIPAddress(final Callback callback) { - String ipAddress = "error"; - String tmp = "0.0.0.0"; - - for (InterfaceAddress address : getInetAddresses()) { - if (!address.getAddress().isLoopbackAddress()) { - tmp = address.getAddress().getHostAddress().toString(); - if (!inDSLITERange(tmp)) { - ipAddress = tmp; - } - } - } + public void getIPAddress(final Promise promise) throws Exception { + new Thread(new Runnable() { + public void run() { + try { + String ipAddress = null; + String tmp = "0.0.0.0"; + + for (InterfaceAddress address : getInetAddresses()) { + if (!address.getAddress().isLoopbackAddress()) { + tmp = address.getAddress().getHostAddress().toString(); + if (!inDSLITERange(tmp)) { + ipAddress = tmp; + } + } + } + promise.resolve(ipAddress); + } catch (Exception e) { + promise.reject("error ", e); + } - callback.invoke(ipAddress); + } + }).start(); + } @ReactMethod - public void getIPV4Address(final Callback callback) { - String ipAddress = "0.0.0.0"; - String tmp = "0.0.0.0"; - - for (InterfaceAddress address : getInetAddresses()) { - if (!address.getAddress().isLoopbackAddress() && address.getAddress() instanceof Inet4Address) { - tmp = address.getAddress().getHostAddress().toString(); - if (!inDSLITERange(tmp)) { - ipAddress = tmp; - } - } - } - - callback.invoke(ipAddress); + public void getIPV4Address(final Promise promise) throws Exception { + new Thread(new Runnable() { + public void run() { + try { + String ipAddress = null; + String tmp = "0.0.0.0"; + + for (InterfaceAddress address : getInetAddresses()) { + if (!address.getAddress().isLoopbackAddress() && address.getAddress() instanceof Inet4Address) { + tmp = address.getAddress().getHostAddress().toString(); + if (!inDSLITERange(tmp)) { + ipAddress = tmp; + } + } + } + promise.resolve(ipAddress); + } catch (Exception e) { + promise.reject("error ", e); + } + + } + }).start(); } diff --git a/ios/RNNetworkInfo.m b/ios/RNNetworkInfo.m index 592c6ae..7a53969 100644 --- a/ios/RNNetworkInfo.m +++ b/ios/RNNetworkInfo.m @@ -24,120 +24,149 @@ @implementation RNNetworkInfo RCT_EXPORT_MODULE(); -RCT_EXPORT_METHOD(getSSID:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(getSSID:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { - NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces()); + @try{ + NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces()); - NSDictionary *SSIDInfo; - NSString *SSID = @"error"; + NSDictionary *SSIDInfo; + NSString *SSID = @"error"; - for (NSString *interfaceName in interfaceNames) { - SSIDInfo = CFBridgingRelease(CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName)); + for (NSString *interfaceName in interfaceNames) { + SSIDInfo = CFBridgingRelease(CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName)); - if (SSIDInfo.count > 0) { - SSID = SSIDInfo[@"SSID"]; - break; + if (SSIDInfo.count > 0) { + SSID = SSIDInfo[@"SSID"]; + break; + } + } + + resolve(SSID); + }@catch (NSException *exception) { + reject(@"error ",@"getSSID",exception.description); // We'll just silently ignore exception. } - callback(@[SSID]); } -RCT_EXPORT_METHOD(getBSSID:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(getBSSID:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { - NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces()); - NSString *BSSID = @"error"; + @try{ + NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces()); + NSString *BSSID = @""; - for (NSString* interface in interfaceNames) - { - CFDictionaryRef networkDetails = CNCopyCurrentNetworkInfo((CFStringRef) interface); - if (networkDetails) + for (NSString* interface in interfaceNames) { - BSSID = (NSString *)CFDictionaryGetValue (networkDetails, kCNNetworkInfoKeyBSSID); - CFRelease(networkDetails); + CFDictionaryRef networkDetails = CNCopyCurrentNetworkInfo((CFStringRef) interface); + if (networkDetails) + { + BSSID = (NSString *)CFDictionaryGetValue (networkDetails, kCNNetworkInfoKeyBSSID); + CFRelease(networkDetails); + } } + + resolve(BSSID); + }@catch (NSException *exception) { + reject(@"error ",@"getBSSID",exception.description); // We'll just silently ignore exception. } - callback(@[BSSID]); } -RCT_EXPORT_METHOD(getBroadcast:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(getBroadcast:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) + { - NSString *address = @"error"; - NSString *netmask = @"error"; + @try{ + NSString *address = @""; + NSString *netmask = @"error"; - struct ifaddrs *interfaces = NULL; - struct ifaddrs *temp_addr = NULL; - int success = 0; + struct ifaddrs *interfaces = NULL; + struct ifaddrs *temp_addr = NULL; + int success = 0; - success = getifaddrs(&interfaces); + success = getifaddrs(&interfaces); - if (success == 0) { - temp_addr = interfaces; - while(temp_addr != NULL) { - if(temp_addr->ifa_addr->sa_family == AF_INET) { - if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { - address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; - netmask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)]; + if (success == 0) { + temp_addr = interfaces; + while(temp_addr != NULL) { + if(temp_addr->ifa_addr->sa_family == AF_INET) { + if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { + address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; + netmask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)]; - struct in_addr local_addr; - struct in_addr netmask_addr; - inet_aton([address UTF8String], &local_addr); - inet_aton([netmask UTF8String], &netmask_addr); + struct in_addr local_addr; + struct in_addr netmask_addr; + inet_aton([address UTF8String], &local_addr); + inet_aton([netmask UTF8String], &netmask_addr); - local_addr.s_addr |= ~(netmask_addr.s_addr); + local_addr.s_addr |= ~(netmask_addr.s_addr); - address = [NSString stringWithUTF8String:inet_ntoa(local_addr)]; + address = [NSString stringWithUTF8String:inet_ntoa(local_addr)]; + } } + temp_addr = temp_addr->ifa_next; } - temp_addr = temp_addr->ifa_next; } + freeifaddrs(interfaces); + resolve(address); + }@catch (NSException *exception) { + reject(@"error ",@"getBroadcast",exception.description); // We'll just silently ignore exception. } - - freeifaddrs(interfaces); - callback(@[address]); } -RCT_EXPORT_METHOD(getIPAddress:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(getIPAddress:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { - NSString *address = @"error"; + @try { + NSString *address = @""; - struct ifaddrs *interfaces = NULL; - struct ifaddrs *temp_addr = NULL; - int success = 0; + struct ifaddrs *interfaces = NULL; + struct ifaddrs *temp_addr = NULL; + int success = 0; - success = getifaddrs(&interfaces); + success = getifaddrs(&interfaces); - if (success == 0) { - temp_addr = interfaces; - while(temp_addr != NULL) { - if(temp_addr->ifa_addr->sa_family == AF_INET) { - if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { - address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; + if (success == 0) { + temp_addr = interfaces; + while(temp_addr != NULL) { + if(temp_addr->ifa_addr->sa_family == AF_INET) { + if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { + address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; + } } + temp_addr = temp_addr->ifa_next; } - temp_addr = temp_addr->ifa_next; } + freeifaddrs(interfaces); + resolve(address); + }@catch (NSException *exception) { + reject(@"error ",@"getIPAddress",exception.description); // We'll just silently ignore exception. } - - freeifaddrs(interfaces); - callback(@[address]); } - RCT_EXPORT_METHOD(getIPV4Address:(RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD(getIPV4Address:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { - NSArray *searchArray = @[ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv4 ]; - NSDictionary *addresses = [self getAllIPAddresses]; - NSLog(@"addresses: %@", addresses); - - __block NSString *address; - [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) - { - address = addresses[key]; - if(address) *stop = YES; - } ]; - NSString *addressToReturn = address ? address : @"0.0.0.0"; - callback(@[addressToReturn]); + @try{ + NSArray *searchArray = @[ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv4 ]; + NSDictionary *addresses = [self getAllIPAddresses]; + NSLog(@"addresses: %@", addresses); + + __block NSString *address; + [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) + { + address = addresses[key]; + if(address) *stop = YES; + + } ]; + NSString *addressToReturn = address ? address : @"0.0.0.0"; + resolve(addressToReturn); + }@catch (NSException *exception) { + reject(@"error ",@"getIPV4Address",exception.description); // We'll just silently ignore exception. + } + } - (NSDictionary *)getAllIPAddresses From 50da6462c9f11d2173ab10b5275530860bfad807 Mon Sep 17 00:00:00 2001 From: Hossein Mohammadi Date: Thu, 14 Mar 2019 18:15:07 +0330 Subject: [PATCH 2/3] Return null when the native code fails and solve syntax issues --- NetworkInfo.js | 4 +- .../pusherman/networkinfo/RNNetworkInfo.java | 169 +++++++++--------- ios/RNNetworkInfo.m | 149 ++++++++------- package.json | 2 +- 4 files changed, 158 insertions(+), 166 deletions(-) diff --git a/NetworkInfo.js b/NetworkInfo.js index edf825a..d6c0b2d 100644 --- a/NetworkInfo.js +++ b/NetworkInfo.js @@ -1,6 +1,6 @@ -"use strict"; +'use strict'; -import { NativeModules } from "react-native"; +import { NativeModules } from 'react-native'; const { RNNetworkInfo } = NativeModules; const NetworkInfo = { diff --git a/android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java b/android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java index ba62a1e..7bcaa0f 100644 --- a/android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java +++ b/android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java @@ -6,6 +6,7 @@ import android.support.annotation.NonNull; import android.net.wifi.SupplicantState; import android.util.Log; + import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; @@ -22,14 +23,12 @@ import java.util.List; - - public class RNNetworkInfo extends ReactContextBaseJavaModule { WifiManager wifi; public static final String TAG = "RNNetworkInfo"; - public static List 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 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) { @@ -47,123 +46,123 @@ public String getName() { @ReactMethod public void getSSID(final Promise promise) throws Exception { new Thread(new Runnable() { - public void run() { - try { - WifiInfo info = wifi.getConnectionInfo(); - - // This value should be wrapped in double quotes, so we need to unwrap it. - // https://stackoverflow.com/a/34848930/5732760 - String ssid = null; - if (info.getSupplicantState() == SupplicantState.COMPLETED) { - ssid = info.getSSID(); - if (ssid.startsWith("\"") && ssid.endsWith("\"")) { - ssid = ssid.substring(1, ssid.length() - 1); - } - } - promise.resolve(ssid); - } catch (Exception e) { - promise.reject("error ", e); + public void run() { + try { + WifiInfo info = wifi.getConnectionInfo(); + + // This value should be wrapped in double quotes, so we need to unwrap it. + // https://stackoverflow.com/a/34848930/5732760 + String ssid = null; + if (info.getSupplicantState() == SupplicantState.COMPLETED) { + ssid = info.getSSID(); + if (ssid.startsWith("\"") && ssid.endsWith("\"")) { + ssid = ssid.substring(1, ssid.length() - 1); } - } - }).start(); + promise.resolve(ssid); + } catch (Exception e) { + promise.resolve(null); + } + + } + }).start(); } @ReactMethod public void getBSSID(final Promise promise) throws Exception { new Thread(new Runnable() { - public void run() { - try { - WifiInfo info = wifi.getConnectionInfo(); - - // https://stackoverflow.com/a/34848930/5732760 - String bssid = null; - if (info.getSupplicantState() == SupplicantState.COMPLETED) { - bssid = wifi.getConnectionInfo().getBSSID(); - } - promise.resolve(bssid); - } catch (Exception e) { - promise.reject("error ", e); - } - + public void run() { + try { + WifiInfo info = wifi.getConnectionInfo(); + + // https://stackoverflow.com/a/34848930/5732760 + String bssid = null; + if (info.getSupplicantState() == SupplicantState.COMPLETED) { + bssid = wifi.getConnectionInfo().getBSSID(); } - }).start(); + promise.resolve(bssid); + } catch (Exception e) { + promise.resolve(null); + } + + } + }).start(); } @ReactMethod public void getBroadcast(final Promise promise) throws Exception { new Thread(new Runnable() { - public void run() { - try { - String ipAddress = null; + public void run() { + try { + String ipAddress = null; - for (InterfaceAddress address : getInetAddresses()) { - if (!address.getAddress().isLoopbackAddress()/*address.getAddress().toString().equalsIgnoreCase(ip)*/) { - ipAddress = address.getBroadcast().toString(); - } + for (InterfaceAddress address : getInetAddresses()) { + if (!address.getAddress().isLoopbackAddress()/*address.getAddress().toString().equalsIgnoreCase(ip)*/) { + ipAddress = address.getBroadcast().toString(); } - promise.resolve(ipAddress); - } catch (Exception e) { - promise.reject("error ", e); - } - } - }).start(); + promise.resolve(ipAddress); + } catch (Exception e) { + promise.resolve(null); + } + + } + }).start(); } @ReactMethod public void getIPAddress(final Promise promise) throws Exception { new Thread(new Runnable() { - public void run() { - try { - String ipAddress = null; - String tmp = "0.0.0.0"; - - for (InterfaceAddress address : getInetAddresses()) { - if (!address.getAddress().isLoopbackAddress()) { - tmp = address.getAddress().getHostAddress().toString(); - if (!inDSLITERange(tmp)) { - ipAddress = tmp; - } - } + public void run() { + try { + String ipAddress = null; + String tmp = "0.0.0.0"; + + for (InterfaceAddress address : getInetAddresses()) { + if (!address.getAddress().isLoopbackAddress()) { + tmp = address.getAddress().getHostAddress().toString(); + if (!inDSLITERange(tmp)) { + ipAddress = tmp; } - promise.resolve(ipAddress); - } catch (Exception e) { - promise.reject("error ", e); } - + } + promise.resolve(ipAddress); + } catch (Exception e) { + promise.resolve(null); } - }).start(); - + + } + }).start(); + } @ReactMethod public void getIPV4Address(final Promise promise) throws Exception { new Thread(new Runnable() { - public void run() { - try { - String ipAddress = null; - String tmp = "0.0.0.0"; - - for (InterfaceAddress address : getInetAddresses()) { - if (!address.getAddress().isLoopbackAddress() && address.getAddress() instanceof Inet4Address) { - tmp = address.getAddress().getHostAddress().toString(); - if (!inDSLITERange(tmp)) { - ipAddress = tmp; - } + public void run() { + try { + String ipAddress = null; + String tmp = "0.0.0.0"; + + for (InterfaceAddress address : getInetAddresses()) { + if (!address.getAddress().isLoopbackAddress() && address.getAddress() instanceof Inet4Address) { + tmp = address.getAddress().getHostAddress().toString(); + if (!inDSLITERange(tmp)) { + ipAddress = tmp; } } - promise.resolve(ipAddress); - } catch (Exception e) { - promise.reject("error ", e); - } - } - }).start(); + promise.resolve(ipAddress); + } catch (Exception e) { + promise.resolve(null); + } + + } + }).start(); } - private Boolean inDSLITERange (String ip) { + 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 // added this check in getIPAddress and getIPV4Address diff --git a/ios/RNNetworkInfo.m b/ios/RNNetworkInfo.m index 7a53969..850006f 100644 --- a/ios/RNNetworkInfo.m +++ b/ios/RNNetworkInfo.m @@ -29,25 +29,22 @@ @implementation RNNetworkInfo { @try{ NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces()); - + NSDictionary *SSIDInfo; - NSString *SSID = @"error"; - + NSString *SSID = NULL; + for (NSString *interfaceName in interfaceNames) { SSIDInfo = CFBridgingRelease(CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName)); - + if (SSIDInfo.count > 0) { SSID = SSIDInfo[@"SSID"]; break; } - } - resolve(SSID); }@catch (NSException *exception) { - reject(@"error ",@"getSSID",exception.description); // We'll just silently ignore exception. + resolve(NULL); } - } RCT_EXPORT_METHOD(getBSSID:(RCTPromiseResolveBlock)resolve @@ -55,8 +52,8 @@ @implementation RNNetworkInfo { @try{ NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces()); - NSString *BSSID = @""; - + NSString *BSSID = NULL; + for (NSString* interface in interfaceNames) { CFDictionaryRef networkDetails = CNCopyCurrentNetworkInfo((CFStringRef) interface); @@ -66,12 +63,10 @@ @implementation RNNetworkInfo CFRelease(networkDetails); } } - resolve(BSSID); }@catch (NSException *exception) { - reject(@"error ",@"getBSSID",exception.description); // We'll just silently ignore exception. + resolve(NULL); } - } RCT_EXPORT_METHOD(getBroadcast:(RCTPromiseResolveBlock)resolve @@ -79,15 +74,15 @@ @implementation RNNetworkInfo { @try{ - NSString *address = @""; + NSString *address = NULL; NSString *netmask = @"error"; - + struct ifaddrs *interfaces = NULL; struct ifaddrs *temp_addr = NULL; int success = 0; - + success = getifaddrs(&interfaces); - + if (success == 0) { temp_addr = interfaces; while(temp_addr != NULL) { @@ -95,14 +90,14 @@ @implementation RNNetworkInfo if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; netmask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)]; - + struct in_addr local_addr; struct in_addr netmask_addr; inet_aton([address UTF8String], &local_addr); inet_aton([netmask UTF8String], &netmask_addr); - + local_addr.s_addr |= ~(netmask_addr.s_addr); - + address = [NSString stringWithUTF8String:inet_ntoa(local_addr)]; } } @@ -112,7 +107,7 @@ @implementation RNNetworkInfo freeifaddrs(interfaces); resolve(address); }@catch (NSException *exception) { - reject(@"error ",@"getBroadcast",exception.description); // We'll just silently ignore exception. + resolve(NULL); } } @@ -120,14 +115,14 @@ @implementation RNNetworkInfo rejecter:(RCTPromiseRejectBlock)reject) { @try { - NSString *address = @""; - + NSString *address = NULL; + struct ifaddrs *interfaces = NULL; struct ifaddrs *temp_addr = NULL; int success = 0; - + success = getifaddrs(&interfaces); - + if (success == 0) { temp_addr = interfaces; while(temp_addr != NULL) { @@ -142,72 +137,70 @@ @implementation RNNetworkInfo freeifaddrs(interfaces); resolve(address); }@catch (NSException *exception) { - reject(@"error ",@"getIPAddress",exception.description); // We'll just silently ignore exception. + resolve(NULL); } } RCT_EXPORT_METHOD(getIPV4Address:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) - { - @try{ - NSArray *searchArray = @[ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv4 ]; - NSDictionary *addresses = [self getAllIPAddresses]; - NSLog(@"addresses: %@", addresses); - - __block NSString *address; - [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) - { - address = addresses[key]; - if(address) *stop = YES; - - } ]; - NSString *addressToReturn = address ? address : @"0.0.0.0"; - resolve(addressToReturn); - }@catch (NSException *exception) { - reject(@"error ",@"getIPV4Address",exception.description); // We'll just silently ignore exception. - } - +{ + @try{ + NSArray *searchArray = @[ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv4 ]; + NSDictionary *addresses = [self getAllIPAddresses]; + NSLog(@"addresses: %@", addresses); + + __block NSString *address; + [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) + { + address = addresses[key]; + if(address) *stop = YES; + } ]; + NSString *addressToReturn = address ? address : @"0.0.0.0"; + resolve(addressToReturn); + }@catch (NSException *exception) { + resolve(NULL); } - +} + - (NSDictionary *)getAllIPAddresses - { - NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8]; - - // retrieve the current interfaces - returns 0 on success - struct ifaddrs *interfaces; - if(!getifaddrs(&interfaces)) { - // Loop through linked list of interfaces - struct ifaddrs *interface; - for(interface=interfaces; interface; interface=interface->ifa_next) { - if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) { - continue; // deeply nested code harder to read - } - const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr; - char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ]; - if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) { - NSString *name = [NSString stringWithUTF8String:interface->ifa_name]; - NSString *type; - if(addr->sin_family == AF_INET) { - if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) { - type = IP_ADDR_IPv4; - } - } else { - const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr; - if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) { - type = IP_ADDR_IPv6; - } +{ + NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8]; + + // retrieve the current interfaces - returns 0 on success + struct ifaddrs *interfaces; + if(!getifaddrs(&interfaces)) { + // Loop through linked list of interfaces + struct ifaddrs *interface; + for(interface=interfaces; interface; interface=interface->ifa_next) { + if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) { + continue; // deeply nested code harder to read + } + const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr; + char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ]; + if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) { + NSString *name = [NSString stringWithUTF8String:interface->ifa_name]; + NSString *type; + if(addr->sin_family == AF_INET) { + if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) { + type = IP_ADDR_IPv4; } - if(type) { - NSString *key = [NSString stringWithFormat:@"%@/%@", name, type]; - addresses[key] = [NSString stringWithUTF8String:addrBuf]; + } else { + const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr; + if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) { + type = IP_ADDR_IPv6; } } + if(type) { + NSString *key = [NSString stringWithFormat:@"%@/%@", name, type]; + addresses[key] = [NSString stringWithUTF8String:addrBuf]; + } } - // Free memory - freeifaddrs(interfaces); } - return [addresses count] ? addresses : nil; + // Free memory + freeifaddrs(interfaces); } + return [addresses count] ? addresses : nil; +} @end diff --git a/package.json b/package.json index 19c02fe..b2687cb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "react-native-network-info", - "version": "4.0.1", + "version": "5.0.0", "description": "Get local network information", "main": "NetworkInfo.js", "types": "NetworkInfo.d.ts", From c5cf880f3289bbcd3c7e9244be63a5f70fadb382 Mon Sep 17 00:00:00 2001 From: hossein mohammadi Date: Wed, 25 Sep 2019 09:12:19 +0330 Subject: [PATCH 3/3] throw error to js --- NetworkInfo.d.ts | 16 +-- NetworkInfo.js | 52 +++++---- .../pusherman/networkinfo/RNNetworkInfo.java | 49 ++++++--- ios/RNNetworkInfo.m | 104 +++++++++++++++--- 4 files changed, 160 insertions(+), 61 deletions(-) diff --git a/NetworkInfo.d.ts b/NetworkInfo.d.ts index 77c755e..dcba0bf 100644 --- a/NetworkInfo.d.ts +++ b/NetworkInfo.d.ts @@ -1,10 +1,10 @@ export namespace NetworkInfo { - function getSSID(): Promise; - function getBSSID(): Promise; - function getBroadcast(): Promise; - function getIPAddress(): Promise; - function getIPV4Address(): Promise; - function getSubnet(): Promise; - function getGatewayIPAddress(): Promise; - function getFrequency(): Promise; + function getSSID(fallback: any): Promise; + function getBSSID(fallback: any): Promise; + function getBroadcast(fallback: any): Promise; + function getIPAddress(fallback: any): Promise; + function getIPV4Address(fallback: any): Promise; + function getSubnet(fallback: any): Promise; + function getGatewayIPAddress(fallback: any): Promise; + function getFrequency(fallback: any): Promise; } diff --git a/NetworkInfo.js b/NetworkInfo.js index 9f5be2a..b5f8b58 100644 --- a/NetworkInfo.js +++ b/NetworkInfo.js @@ -3,46 +3,56 @@ import { NativeModules, Platform } from "react-native"; const { RNNetworkInfo } = NativeModules; +async function handleError(callback, fallback = null) { + try { + return await callback(); + } catch (error) { + if (__DEV__) console.log(error); + + return fallback; + } +} + const NetworkInfo = { - async getSSID() { - return await RNNetworkInfo.getSSID(); + async getSSID(fallback) { + return await handleError(RNNetworkInfo.getSSID, fallback); }, - async getBSSID() { - return await RNNetworkInfo.getBSSID(); + async getBSSID(fallback) { + return await handleError(RNNetworkInfo.getBSSID, fallback); }, - async getBroadcast() { - return await RNNetworkInfo.getBroadcast(); + async getBroadcast(fallback) { + return await handleError(RNNetworkInfo.getBroadcast, fallback); }, - async getIPAddress() { - return await RNNetworkInfo.getIPAddress(); + async getIPAddress(fallback) { + return await handleError(RNNetworkInfo.getIPAddress, fallback); }, - async getIPV4Address() { - const wifiIP = await RNNetworkInfo.getWIFIIPV4Address(); - if (wifiIP && wifiIP !== '0.0.0.0') { + async getIPV4Address(fallback) { + const wifiIP = await handleError(RNNetworkInfo.getWIFIIPV4Address); + if (wifiIP) { return wifiIP; } - - return await RNNetworkInfo.getIPV4Address(); + + return await handleError(RNNetworkInfo.getIPV4Address, fallback); }, - async getGatewayIPAddress() { - return await RNNetworkInfo.getGatewayIPAddress(); + async getGatewayIPAddress(fallback) { + return await handleError(RNNetworkInfo.getGatewayIPAddress, fallback); }, - async getSubnet() { - return await RNNetworkInfo.getSubnet(); + async getSubnet(fallback) { + return await handleError(RNNetworkInfo.getSubnet, fallback); }, - async getFrequency() { + async getFrequency(fallback) { if (Platform.OS !== 'android') { - return null; + return fallback; } - return await RNNetworkInfo.getFrequency(); - } + return await handleError(RNNetworkInfo.getFrequency, fallback); + }, }; module.exports = { NetworkInfo }; diff --git a/android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java b/android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java index a2560a4..7b9bb5f 100644 --- a/android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java +++ b/android/src/main/java/com/pusherman/networkinfo/RNNetworkInfo.java @@ -4,6 +4,9 @@ import android.net.DhcpInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; + +import androidx.annotation.NonNull; + import android.net.wifi.SupplicantState; import android.util.Log; @@ -57,10 +60,12 @@ public void run() { if (ssid.startsWith("\"") && ssid.endsWith("\"")) { ssid = ssid.substring(1, ssid.length() - 1); } + } else { + throw new Exception("The Supplicant State has not been completed"); } promise.resolve(ssid); } catch (Exception e) { - promise.resolve(null); + promise.reject(e); } } @@ -77,11 +82,13 @@ public void run() { // https://stackoverflow.com/a/34848930/5732760 String bssid = null; if (info.getSupplicantState() == SupplicantState.COMPLETED) { - bssid = wifi.getConnectionInfo().getBSSID(); + bssid = info.getBSSID(); + } else { + throw new Exception("The Supplicant State has not been completed"); } promise.resolve(bssid); } catch (Exception e) { - promise.resolve(null); + promise.reject(e); } } @@ -101,9 +108,12 @@ public void run() { ipAddress = address.getBroadcast().toString(); } } + if (ipAddress == null) { + throw new Exception("Broadcast address not found"); + } promise.resolve(ipAddress); } catch (Exception e) { - promise.resolve(null); + promise.reject(e); } } @@ -126,9 +136,12 @@ public void run() { } } } + if (ipAddress == null) { + throw new Exception("IP address not found"); + } promise.resolve(ipAddress); } catch (Exception e) { - promise.resolve(null); + promise.reject(e); } } @@ -152,9 +165,12 @@ public void run() { } } } + if (ipAddress == null) { + throw new Exception("IPV4 address not found"); + } promise.resolve(ipAddress); } catch (Exception e) { - promise.resolve(null); + promise.reject(e); } } @@ -176,7 +192,7 @@ public void run() { (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)); promise.resolve(stringip); }catch (Exception e) { - promise.resolve(null); + promise.reject(e); } } }).start(); @@ -205,8 +221,9 @@ public void run() { return; } } + throw new Exception("Subnet not found"); } catch (Exception e) { - promise.resolve("0.0.0.0"); + promise.reject(e); } } }).start(); @@ -220,15 +237,15 @@ public void run() { DhcpInfo dhcpInfo = wifi.getDhcpInfo(); int gatewayIPInt = dhcpInfo.gateway; String gatewayIP = String.format( - "%d.%d.%d.%d", - ((gatewayIPInt) & 0xFF), - ((gatewayIPInt >> 8 ) & 0xFF), - ((gatewayIPInt >> 16) & 0xFF), - ((gatewayIPInt >> 24) & 0xFF) + "%d.%d.%d.%d", + ((gatewayIPInt) & 0xFF), + ((gatewayIPInt >> 8 ) & 0xFF), + ((gatewayIPInt >> 16) & 0xFF), + ((gatewayIPInt >> 24) & 0xFF) ); promise.resolve(gatewayIP); } catch (Exception e) { - promise.resolve(null); + promise.reject(e); } } }).start(); @@ -243,7 +260,7 @@ public void run() { final float frequency = info.getFrequency(); promise.resolve(frequency); } catch (Exception e) { - promise.resolve(null); + promise.reject(e); } } }).start(); @@ -270,7 +287,7 @@ private String intToIP(int ip) { private Boolean inDSLITERange(String ip) { // Fixes issue https://github.com/pusherman/react-native-network-info/issues/43 - // Based on comment + // 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); diff --git a/ios/RNNetworkInfo.m b/ios/RNNetworkInfo.m index 115bdbb..a10b328 100644 --- a/ios/RNNetworkInfo.m +++ b/ios/RNNetworkInfo.m @@ -46,9 +46,17 @@ @implementation RNNetworkInfo break; } } + + if (SSID == NULL) { + NSException* exception = [NSException + exceptionWithName:@"SSIDNotFoundException" + reason:@"SSID Not Found" + userInfo:nil]; + @throw exception; + } resolve(SSID); }@catch (NSException *exception) { - resolve(NULL); + reject(exception); } } #endif @@ -70,9 +78,17 @@ @implementation RNNetworkInfo CFRelease(networkDetails); } } + + if (BSSID == NULL) { + NSException* exception = [NSException + exceptionWithName:@"BSSIDNotFoundException" + reason:@"BSSID Not Found" + userInfo:nil]; + @throw exception; + } resolve(BSSID); }@catch (NSException *exception) { - resolve(NULL); + reject(exception); } } #endif @@ -111,11 +127,28 @@ @implementation RNNetworkInfo } temp_addr = temp_addr->ifa_next; } + } else { + freeifaddrs(interfaces); + + NSException* exception = [NSException + exceptionWithName:@"BroadcastNotFoundException" + reason:@"getifaddrs has been Not successful" + userInfo:nil]; + @throw exception; } + freeifaddrs(interfaces); + + if (address == NULL) { + NSException* exception = [NSException + exceptionWithName:@"BroadcastNotFoundException" + reason:@"Broadcast Not Found" + userInfo:nil]; + @throw exception; + } resolve(address); }@catch (NSException *exception) { - resolve(NULL); + reject(exception); } } @@ -141,11 +174,28 @@ @implementation RNNetworkInfo } temp_addr = temp_addr->ifa_next; } + } else { + freeifaddrs(interfaces); + + NSException* exception = [NSException + exceptionWithName:@"IPAddressNotFoundException" + reason:@"getifaddrs has been Not successful" + userInfo:nil]; + @throw exception; } freeifaddrs(interfaces); + + if (address == NULL) { + NSException* exception = [NSException + exceptionWithName:@"IPAddressNotFoundException" + reason:@"IPAddress Not Found" + userInfo:nil]; + @throw exception; + } + resolve(address); }@catch (NSException *exception) { - resolve(NULL); + reject(exception); } } @@ -161,7 +211,7 @@ @implementation RNNetworkInfo } resolve(ipString); }@catch (NSException *exception) { - resolve(NULL); + reject(exception); } } @@ -179,10 +229,18 @@ @implementation RNNetworkInfo address = addresses[key]; if(address) *stop = YES; } ]; - NSString *addressToReturn = address ? address : @"0.0.0.0"; - resolve(addressToReturn); + + if (address) { + resolve(address); + } + NSException* exception = [NSException + exceptionWithName:@"IPV4AddressNotFoundException" + reason:@"IPV4Address Not Found" + userInfo:nil]; + @throw exception; + } }@catch (NSException *exception) { - resolve(NULL); + reject(exception); } } @@ -204,10 +262,17 @@ @implementation RNNetworkInfo address = addresses[key]; if(address) *stop = YES; } ]; - NSString *addressToReturn = address ? address : @"0.0.0.0"; - resolve(addressToReturn); + if(address){ + resolve(address); + } else { + NSException* exception = [NSException + exceptionWithName:@"WIFIIPV4AddressNotFoundException" + reason:@"WIFIIPV4Address Not Found" + userInfo:nil]; + @throw exception; + } }@catch (NSException *exception) { - resolve(NULL); + reject(exception); } } @@ -215,7 +280,7 @@ @implementation RNNetworkInfo rejecter:(RCTPromiseRejectBlock)reject) { @try { - NSString *netmask = @"error"; + NSString *netmask = NULL; struct ifaddrs *interfaces = NULL; struct ifaddrs *temp_addr = NULL; @@ -242,11 +307,18 @@ @implementation RNNetworkInfo } } freeifaddrs(interfaces); - - NSString *addressToReturn = netmask ? netmask : @"0.0.0.0"; - resolve(addressToReturn); + + if (netmask == NULL) { + NSException* exception = [NSException + exceptionWithName:@"IPV4AddressNotFoundException" + reason:@"IPV4Address Not Found" + userInfo:nil]; + @throw exception; + } + + resolve(netmask); } @catch (NSException *exception) { - resolve(NULL); + reject(exception); } }