Giter Site home page Giter Site logo

pusherman / react-native-network-info Goto Github PK

View Code? Open in Web Editor NEW
353.0 9.0 105.0 105 KB

React Native library for getting information about the devices network

License: MIT License

JavaScript 1.87% Objective-C 20.11% Java 21.69% Ruby 0.95% C 55.37%
react-native ios android-library ios-lib android networking network

react-native-network-info's Introduction

react-native-network-info

React Native library for getting information about the devices network

Requirements

Version 3+ requires RN 0.47 or higher Version 2+ requires RN 0.40 - RN 0.46

Installation

npm install react-native-network-info --save

or

yarn add react-native-network-info

Linking the library

Using React Native >= 0.60

Linking the package manually is not required anymore with Autolinking.

iOS also requires CocoaPods install

$ cd ios && pod install && cd ..

Using React Native < 0.60

$ react-native link react-native-network-info

Usage

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

// Get Local IP
NetworkInfo.getIPAddress().then(ipAddress => {
  console.log(ipAddress);
});

// Get IPv4 IP (priority: WiFi first, cellular second)
NetworkInfo.getIPV4Address().then(ipv4Address => {
  console.log(ipv4Address);
});

// Get Broadcast
NetworkInfo.getBroadcast().then(broadcast => {
  console.log(broadcast);
});

// Get SSID
NetworkInfo.getSSID().then(ssid => {
  console.log(ssid);
});

// Get BSSID
NetworkInfo.getBSSID().then(bssid => {
  console.log(bssid);
});

// Get Subnet
NetworkInfo.getSubnet().then(subnet => {
  console.log(subnet);
});

// Get Default Gateway IP
NetworkInfo.getGatewayIPAddress().then(defaultGateway => {
  console.log(defaultGateway);
});

// Get frequency (supported only for Android)
NetworkInfo.getFrequency().then(frequency => {
  console.log(frequency);
});

Manually Linking the Library

If react-native link fails and you are not using the auto linking provided in React Native >= 0.60

iOS

  1. In XCode, in the project navigator, right click Libraries ➜ Add Files to [your project's name]

  2. Go to node_modules ➜ react-native-network-info and add the .xcodeproj file

  3. Add RNNetworkInfo.a to Build Phases -> Link Binary With Libraries

Run your project (Cmd+R)

Android

  1. Add the following lines to android/settings.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:

    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
    
  4. Add the compile line to the dependencies in android/app/build.gradle:

    dependencies {
        ...
        compile project(':react-native-network-info')
    }
  5. Add the import and link the package in MainApplication.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.

react-native-network-info's People

Contributors

airamrguez avatar chirag04 avatar codlab avatar davidstoneham avatar dylanvann avatar hosseinmd avatar indraastra avatar jacob-meacham avatar jgfidelis avatar kamedakyosuke avatar keeth avatar kulyk avatar lfkwtz avatar markygab avatar martinffx avatar nnnnnoel avatar npomfret avatar parrotmac avatar pusherman avatar rafcontreras avatar rapsssito avatar richardvclam avatar robwalkerco avatar rolandandrena avatar shashfrankenstien avatar wuwen23333 avatar yosimasu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-network-info's Issues

getBSSID is not working in android PIE

i am using
"react-native-network-info": "^3.2.2",
my react version is
"react": "16.0.0-beta.5",
"react-native": "0.49.3",

i am using react-native-network-info to get network BSSID
this was wasworking fine untill my user update thier Android OS to Android PIE

it always return 02:00:00:00:01:00 in android PIE devices

anyone has any idea about this

Don't switch to import

Please don't do a92b6e4.

Even if you pre-'babelify' before pushing to npm, it will cause trouble for forks that need to npm/yarn install/add directly from github.

getBroadcast() could be null in android on some interfaces

    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.net.InetAddress.toString()' on a null object reference
        at com.pusherman.networkinfo.RNNetworkInfo.getBroadcast(RNNetworkInfo.java:63)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)
        at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:160)
        at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:754)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)
        at android.os.Looper.loop(Looper.java:163)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:192)
        at java.lang.Thread.run(Thread.java:760)

A possible fix would be add some check to broadcast address

    @ReactMethod
    public void getBroadcast(/*@NonNull String ip, */final Callback callback) {
        String ipAddress = null;

        for (InterfaceAddress address : getInetAddresses()) {
            if (!address.getAddress().isLoopbackAddress()/*address.getAddress().toString().equalsIgnoreCase(ip)*/) {
                InetAddress broadCast = address.getBroadcast();
                if (broadCast != null){
                    ipAddress = broadCast.toString();
                }
            }
        }

        callback.invoke(ipAddress);
    }

How to be certain that the callback returns an error

I was wondering if there is a correct way to know if there was an error retrieving the network data requested in the callback, I think this is not a good way to do that:

NetworkInfo.getSSID(ssid => {
  if (ssid == "error") {
     // error
   } else {
    // OK
   }
});

TypeError: undefined is not an object (evaluating 'RNNetworkInfo.getSSID')

Hello!

I'm trying to use this library on an Android smartphone (not emulator) and I can't really get any information from it. I believe all the setup has been done right, so it should be working.

What happens is that when I try to use any NetworkInfo methods it always says:

TypeError: undefined is not an object (evaluating 'RNNetworkInfo.getSSID')

This error is located at:
    in App (at registerRootComponent.js:34)
    in RootErrorBoundary (at registerRootComponent.js:33)
    in ExpoRootComponent (at renderApplication.js:35)
    in RCTView (at View.js:113)
    in View (at AppContainer.js:102)
    in RCTView (at View.js:113)
    in View (at AppContainer.js:122)
    in AppContainer (at renderApplication.js:34)
- node_modules/react-native-network-info/NetworkInfo.js:8:18 in getSSID
* App.js:21:24 in render

I'm not sure what can be wrong with this... This is a clear installation with create-react-native-app and after react-native eject. Also worth noting that I'm using Expo within the project...

Any tips on what's happening? If you need more info, just let me know exactly what info.

Thanks in advance!

Android support?

Hi @pusherman, I was just wondering if you had any plans to implement Android support for this library. If not, would you mind if I took a crack at it and submitted a PR to avoid spawning a whole new library?

I've tested this out on iOS and it works perfectly by the way, so thanks!

NetworkInfo functions always return error on IOS

I am using IOS 11.0 Simulator and XCODE 9.0.
My React Native version is 0.49.3, react-native-network-info version is 3.0.0.

This is my code on my app:

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


  componentDidMount() {
    NetworkInfo.getSSID((ip) => {
        alert(ip);
    });
  }

what it show is:
screen shot 2017-10-14 at 11 58 20 pm

How can i fix this? I installed it according to the docs and it doesn't have any building error?

More Features

do you have any future plans regarding this package?
Maybe getBSSID (endpoint) for ex?
I suggest BSSID because is usually very useful when working in some environment where there are lots of endpoints but all have the same SSID

getBSSID always return 02:00:00:00:00:00

"react": "16.0.0-beta.5",
"react-native": "0.49.3",
"react-native-network-info": "^3.2.2",

Issue : some device start sending bssid 02:00:00:00:00:00 from every wifi/network

expected result: it should return different Bssid with different wifi network

error setup

image
image

use
"react-native": "0.49.3",
"react-native-network-info": "^3.2.2",

Add ping and wake features

Are you interested in adding ping and wake functions ?

I'm guessing you're not, since the library is named network-info, but maybe create a network-ops library or similar ?

Problems getting SSID to work in Simulator

Hello,

I have problems getting SSID when I'm running the XCode iOS simulator. I am running it as a iphone 6S with iOS 9.2. No interfaces is found and 'error' is returned. Should it be able to work in the simulator or what can I have made wrong? I can get the IP without any problems.

thanks!

ios run error in the simulator

Hello!

<React/RCTBridge.h> is not found.

node_modules/react-native-network-info/ios/RNNetworkInfo.h:10:9: fatal error: 'React/RCTBridge.h' file not found
#import <React/RCTBridge.h>
^
1 error generated.

"react": "^15.4.1",
"react-native": "^0.39.2",
"react-native-network-info": "^1.0.0"

Could not find intellij-core.jar (com.android.tools.external.com-intellij:intellij-core:26.0.1)

Hello i have this issue with ./gradlew clean command

A problem occurred configuring project ':react-native-network-info'.

Could not resolve all artifacts for configuration ':react-native-network-info:classpath'.
Could not find intellij-core.jar (com.android.tools.external.com-intellij:intellij-core:26.0.1).
> Searched in the following locations:
> https://jcenter.bintray.com/com/android/tools/external/com-intellij/intellij-core/26.0.1/intellij-core-26.0.1.jar

An idea ?

getSSID() and getBSSID() seem not work

Hello,
First, appreciate that you put the contribution to the RN-related network development.

I am now attempting to experiment this package in my project but it seems I occurred non-expected results when using them, i.e., getSSID() and getBSSID(). Both Android and iOS simulators I run on always give me error message. Is there any version requirements like for RN or others? Please help me let it work, so thanks to you in advance. ;)

Below key snippet are placed in component's onPress() event.

// Get SSID
NetworkInfo.getSSID(ssid => {
  console.log(ssid);
});

// Get BSSID
NetworkInfo.getBSSID(ssid => {
  console.log(ssid);
});

After the component is pressed, get two 'error' in my debug console.

// for iOS
error
error

// for Android
<unknown ssid>
null

TypeError: _reactNativeNetworkInfo2.default.getSSID is not a function

Using the getSSID() I'm getting the error:
TypeError: _reactNativeNetworkInfo2.default.getSSID is not a function

Running on react-native-network-info 2.2.0 & react-native 0.45.1.
Rolling back to react-native-network-info 1.0.0 & react-native 0.45.1 works fine.

Also worth noting, I only tested version 2.2.0 on iOS.

this is an error happening on android when making a release

Error: The WIFI_SERVICE must be looked up on the Application context or memory will leak on devices < Android N. Try changing reactContext to reactContext.getApplicationContext() [WifiManagerLeak]
wifi = (WifiManager)reactContext.getSystemService(Context.WIFI_SERVICE);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Explanation for issues of type "WifiManagerLeak":
On versions prior to Android N (24), initializing the WifiManager via
Context#getSystemService can cause a memory leak if the context is not the
application context. Change context.getSystemService(...) to
context.getApplicationContext().getSystemService(...).

Android should add this info for accessing valid SSID instead of unknown

async function requestPermission() {

    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          'title': 'Wifi networks',
          'message': 'We need your permission in order to find wifi networks'
        }
      )
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("Thank you for your permission! :)");
      } else {
        console.log("You will not able to retrieve wifi available networks list");
      }
    } catch (err) {
      console.warn(err)
    }
}

And add these to AndroidManifest.xml

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

async/await feature

Hi.
is there anyway to use await for getting network info? I can't use callback.

Package is overweighted

Hi,

After a npm install of your package, the directory size is 61M, mostly due to android build directory, embedding stuff which should not be commited

You should clean that, it's totally useless and horrible for users :)

Wifi List

Hi there,
great work. Any chance this can be extended to get all wifi list and connect to specific wifi

Thanks,

Vinay.

Add podspec

Would be handy for CocoaPods users, thanks!

Error Installing library

****/node_modules/react-native-network-info/ios/RNNetworkInfo.h:10:9: 'React/RCTBridge.h' file not found

This is my config.

screen shot 2017-03-14 at 9 45 04 am

screen shot 2017-03-14 at 9 45 29 am

screen shot 2017-03-14 at 9 45 44 am

Can't get ip address for iOS 11.2

I keep getting the following error when running the app I'm developing on the device:
TCP Conn 0x1c4572300 Failed : error 0:61 [61]

Hence when trying to get the IP address I keep receiving error! has anyone else experienced this?

急,急,急!升级了IOS 12后,getSSID()全部返回Error了

 如题,最近升级IOS 12后,发现调用getSSID()后,老是返回Error, 没有正常返回SSID列表。 但是在IOS 11.4下测试,则一切正常。 

 请大神帮忙看看是什么原因呢? 现在升级IOS 12的人越来越多了,可能会对APP的体验造成不好的影响。

 在此感谢!

NetworkInfo.getIPV4Address returns wrong IP address (Android)

This is a weird one -- it works fine on a Nexus 6 I have that's running Android 6.0.1, but on my Pixel 2 running 8.1.0 NetworkInfo.getIPV4Address is returning the wrong IP address.

I'm using it as expected:

        NetworkInfo.getIPV4Address(ip => {
            console.warn(ip);
        });

On my Pixel 2 the IP address this function is returning is 192.0.0.4, but when I go into my Wifi settings to check my real IP address is 192.168.0.100 (for example).

Any idea what could be causing this discrepancy and how to fix it?

Data Usage

I have a client requesting a feature to capture the iPhone data usage to display - can react-native-network-info help?

Android installation

Hi, in docs it says that I have to modify the MainActivity.java file. But mine looks a little bit different:

package com.myapp;

import com.facebook.react.ReactActivity;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "MyApp";
    }
}

So how can I install it?

I'm using ReactNative 0.41

no typescript support

If you could please bump the version to introduce the typescript support to the package

getSSID not working on IOS device (real)

Hi,
I cannot detect SSID name on the real Iphone.
I've this error

#object[TypeError TypeError: undefined is not an object (evaluating 'RNNetworkInfo.getSSID')]

No problem by using an android device.

IOS 10.3.2
"react": "^16.0.0-alpha.6",
"react-native": "^0.44.0"
"react-native-network-info": "^2.0.0"

ip = "error"

Hi! I can't get the current device IP on iOS simulator. I'm getting IP = error.

I'm currently tehtering the phone internet connection to my mac because I'm having issues with my broadband provider, maybe that's the issue.

Just let me know if I can test something.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.