rojohub / react-native-ping Goto Github PK
View Code? Open in Web Editor NEWHighly accurate ICMP Ping controller for React Native
Home Page: https://www.npmjs.com/package/react-native-ping
Highly accurate ICMP Ping controller for React Native
Home Page: https://www.npmjs.com/package/react-native-ping
Is there any way to calculate cellular or wifi data usage or some kind of statistics?
For eg I have this kind of requirement, If I click on button named "Start" the data usage calculation should start and when I press "Stop" button, then a label should show how much data I have used.
Can I get any help from this package?
const ms = await Ping.start("114.114.114.114"); &
const result = await Ping.getTrafficStats();
returns null
BUILD FAILED in 5s
15 actionable tasks: 12 executed, 3 up-to-date
error Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html
error Command failed: gradlew.bat app:installDebug. Run CLI with --verbose flag for more details.
C:\Users\username\Documents\JS projects\pingtest>react-native run-android
info Starting JS server...
info Building and installing the app on the device (cd android && gradlew.bat app:installDebug)...
Configure project :app
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html
Task :react-native-ping:compileDebugJavaWithJavac
C:\Users\username\Documents\JS projects\pingtest\node_modules\react-native-ping\android\src\main\java\com\reactlibrary\RNReactNativePingModule.java:28: error: reference to reject is ambiguous
promise.reject(error.getCode(), error.getMessage(), null);
^
both method reject(String,String,Throwable) in Promise and method reject(String,String,WritableMap) in Promise match
C:\Users\username\Documents\JS projects\pingtest\node_modules\react-native-ping\android\src\main\java\com\reactlibrary\RNReactNativePingModule.java:54: error: reference to reject is ambiguous
promise.reject(error.getCode(), error.getMessage(), null);
^
both method reject(String,String,Throwable) in Promise and method reject(String,String,WritableMap) in Promise match
C:\Users\username\Documents\JS projects\pingtest\node_modules\react-native-ping\android\src\main\java\com\reactlibrary\RNReactNativePingModule.java:67: error: reference to reject is ambiguous
promise.reject(error.getCode(), error.getMessage(), null);
^
both method reject(String,String,Throwable) in Promise and method reject(String,String,WritableMap) in Promise match
3 errors
Task :react-native-ping:compileDebugJavaWithJavac FAILED
FAILURE: Build failed with an exception.
Compilation failed; see the compiler error output for details.
Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
Get more help at https://help.gradle.org
BUILD FAILED in 7s
15 actionable tasks: 1 executed, 14 up-to-date
error Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html
error Command failed: gradlew.bat app:installDebug. Run CLI with --verbose flag for more details.
I have integrated this module to detect for internet access by pinging Google DNS (8.8.8.8). This works just fine, but one of the first times it pings, on starting the app on iOS, the module throws a DNS error, despite me pinging an IP directly.
This is the error message: 域名解析失败
I have resolved it by just triggering another ping if I get this error, but I think it is a bug.
Looking at your code, I think this module should have a check and not try to resolve the IP for IPs.
The Android package name "com.reactlibrary" is too general, so can you change it to something else?
Duplicate error has occurred when used with a library with the same package name "com.reactlibrary".
help with this issue i dont know how fix them
Facing PingUtil_Message_HostErrorUnknown issue in the version "react-native-ping": "^1.2.6" and
React native version "0.68.2"
Ping "youtube.com" or other url will result in error "PingUtil_Message_HostErrorNotSetHost". We sometimes use it to ping DDNS server.
Compile error after upgrading to version 1.2.0.
node_modules/react-native-ping/ios/GBPing/GBPing.m:6:9: fatal error: 'LHDefinition.h' file not found
#import "LHDefinition.h"
Render freeze when using Ping, unusable UI
Android while(true) PingUtil.java L306 (NEVER DO THIS)
*** -[NSThread startAndReturnError:]: Thread creation failed with error 35
for (let i = 1; i < 255; i++) {
try {
const ms = await Ping.start(`${NetworkIPAddressPrefix}.${i}`, { timeout: 50 });
if (ms !== undefined && ms !== null) {
ipsFound.push(`${NetworkIPAddressPrefix}.${i}`);
}
} catch (error : any) {
console.log("ERROR", error);
}
}
"react": "18.2.0",
"react-native": "0.72.6",
// google IP 172.217.24.46
// version 1.2.4
//
// "react": "16.13.1",
// "react-native": "0.63.0",
try {
const ms = await Ping.start('172.217.24.46', {timeout: 1000});
console.log(ms);
} catch (error) {
console.log('special code', error.code, error.message);
}
If I try to build I get the following error:
* What went wrong:
A problem occurred configuring project ':react-native-ping'.
> Could not resolve all artifacts for configuration ':react-native-ping:classpath'.
> Could not find com.android.tools.build:gradle:3.3.2.
Searched in the following locations:
- https://jcenter.bintray.com/com/android/tools/build/gradle/3.3.2/gradle-3.3.2.pom
- https://jcenter.bintray.com/com/android/tools/build/gradle/3.3.2/gradle-3.3.2.jar
Required by:
project :react-native-ping
This is due to react-native-ping not having google() in the repositories list in its build.gradle.
Hello
I've this error in log:
special code undefined Cannot read property 'start' of undefined
`import React from "react";
import { Text } from "native-base";
import Ping from "react-native-ping";
const Home = (props) => {
React.useEffect(() => {
(async () => {
try {
const ms = await Ping.start("114.114.114.114", { timeout: 1000 });
console.log(ms);
} catch (error) {
console.log(error.message);
}
})();
}, []);
return (
<>
Hi
</>
);
};
export default Home;
`
RESPONSE: null is not an object (evaluating 'RNReactNativePing.start')
Calling the ping function with an ip like 2.34.5.6 which does not exist causes the promise on the start functions to never complete. The code hangs at line 379 in the GBPing.m file.
bytesRead = recvfrom(self.socket, buffer, kBufferSize, 0, (struct sockaddr *)&addr, &addrLen);
A timeout can be added with the following code right before the socket call. This is a timeout of 5 seconds.
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
if (setsockopt(self.socket, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0) {
NSLog(@"Set Timeput Error");
}
This does keep the function from hanging at this point, however it still does not cause a reject on the promise. It would be helpful to be able to exit with a reject on the promise if the socket timeout occurs.
const myFn = async () => { let test = await Ping.getTrafficStats(); console.warn(test); }
So, I am doing like that, and speeds are always 0. For example:
{"receivedNetworkSpeed": "0B/s", "receivedNetworkTotal": "153.4MB", "sendNetworkSpeed": "0B/s", "sendNetworkTotal": "22.2MB"}
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: undefined@undefined
npm ERR! Found: [email protected]
npm ERR! node_modules/react-native
npm ERR! react-native@"~0.63.4" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react-native@"^0.41.2 || ^0.57.0" from [email protected]
npm ERR! node_modules/react-native-ping
npm ERR! react-native-ping@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
import android.support.v4.util.ArrayMap;
Do you plan to migrate to androidX version?
On the following piece of code
[ping startPingingWithBlock:^(GBPingSummary *summary) {
if (!ping) {
return;
}
resolve(@(@(summary.rtt * 1000).intValue));
[ping stop];
ping = nil;
} fail:^(NSError *_Nonnull error) {
if (!ping) {
return;
}
reject(@(error.code).stringValue,error.domain,error);
[ping stop];
ping = nil;
}];
there is a flaw: there is no guarantee the resolve (or reject) call will be finished before the second ping arrive, which would result on a fatal issue as those handlers can only be called once
those handlers should either :
for those encountering the issue before it is corrected, you can handle the ping answer in js using a
setTimeout(() => { // do your stuff} , 0)
Hi!
I always get PingUtil_Message_HostErrorUnknown even though the IP address works. I have tried on 2 emulators and 1 physical device (all android) and its same on all. Same if you ping 8.8.8.8.
However, pinging 127.0.0.1 works. Any ideas what could be wrong?
Dear sir,
please help me. i cannot install i got error
PS D:\Source\2019\ReactNative\test1> npm install react-native-ping --save
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react-native
npm ERR! react-native@"0.67.4" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react-native@"^0.41.2 || ^0.57.0" from [email protected]
npm ERR! node_modules/react-native-ping
npm ERR! react-native-ping@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\Chukiat\AppData\Local\npm-cache\eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Chukiat\AppData\Local\npm-cache_logs\2022-03-23T06_56_36_238Z-debug.log
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These updates are currently rate-limited. Click on a checkbox below to force their creation now.
These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.
These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
@babel/core
, @babel/runtime
)com.facebook.flipper:flipper-fresco-plugin
, com.facebook.flipper:flipper-network-plugin
, com.facebook.flipper:flipper
)react
, react-test-renderer
)babel-jest
, jest
)react
, react-test-renderer
)example/ios/Podfile
android/build.gradle
com.android.tools.build:gradle 3.3.2
example/android/gradle.properties
com.facebook.flipper:flipper 0.54.0
com.facebook.flipper:flipper-network-plugin 0.54.0
com.facebook.flipper:flipper-fresco-plugin 0.54.0
example/android/settings.gradle
example/android/build.gradle
com.android.tools.build:gradle 3.5.3
example/android/app/build.gradle
androidx.swiperefreshlayout:swiperefreshlayout 1.0.0
example/android/gradle/wrapper/gradle-wrapper.properties
gradle 6.2
example/package.json
react 16.13.1
react-native 0.63.4
react-native-ping ^1.2.5
@babel/core ^7.8.4
@babel/runtime ^7.8.4
@react-native-community/eslint-config ^1.1.0
babel-jest ^25.1.0
eslint ^6.5.1
jest ^25.1.0
metro-react-native-babel-preset ^0.59.0
react-test-renderer 16.13.1
package.json
react-native ^0.41.2 || ^0.57.0 || ^0.68.0 || ^0.70.0
if (start) { clearInterval(interval) setStart(false) }else{ setStart(true) interval = setInterval(() => { Ping.start('8.8.8.8', { timeout: 1000 }).then(ms => { setMs(ms); data.push(ms); console.log(ms) }).catch(err => console.log(err)); }, 1000); }
SetInterval cannot stop the ping request, so the request always sent and cannot stopped
Hi! 👋
Firstly, thanks for your work on this project! 🙂
Today I used patch-package to patch [email protected]
for the project I'm working on.
Here is the diff that solved my problem:
diff --git a/node_modules/react-native-ping/index.d.ts b/node_modules/react-native-ping/index.d.ts
new file mode 100644
index 0000000..25bd7a4
--- /dev/null
+++ b/node_modules/react-native-ping/index.d.ts
@@ -0,0 +1,17 @@
+class Ping {
+ /**
+ *
+ * Get RTT (Round-trip delay time)
+ *
+ * @static
+ * @param {string} ipAddress - For example : 8.8.8.8
+ * @param {Object} option - Some optional operations
+ * @param {number} option.timeout - timeout
+ * @returns
+ * @memberof Ping
+ */
+ static async start(ipAddress:string, option:{timeout:number}|any):any
+ static async getTrafficStats():any
+}
+
+export default Ping;
\ No newline at end of file
This issue body was partially generated by patch-package.
If I ping a good address
ms = await Ping.start('8.8.8.8'); //works
then a bad address
ms = await Ping.start('8.8.8.9'); //fails
then trying to ping the good address again always fails unless I restart the app
ms = await Ping.start('8.8.8.8'); //fails
Is there anyway to 'reset' the library to prevent this problem.
I have an app which calls ping.start quite frequently. Leave it running long enough and it will eventually crash due to hitting the assert(NO)
on line 526 of GBPing.m where it does a switch on the value of self.hostAddressFamily. Occasionally, the value is 0 (and this can also be induced manually by setting a breakpoint on line 516).
Is there any reason why that default cannot be removed? When I comment it out, nothing seems to explode and the crash doesn't occur anymore.
(I did notice this other, non-React Native GBPing does this instead of assert(NO):
err = errno;
return;
However, when I try changing it to that, we soon crash due to another race condition: the reject callback in the 'start' method in RNReactNativePing.m gets called twice, once in the fail block (line 57) then again in the dispatch_after block (line 61) which causes a fatal 'Illegal callback invocation from native module' error.)
I consistently receive an 'undefined' response for Ping.start in both the simulator and emulator.
I'm using RN version 0.72.
Could anyone help me with this issue?
And also I face this type issue and can't resolve it by install the type.
cc: @RoJoHub
No matter witch server, it always returns PingUtil_Message_HostErrorUnknown. I'm using it for Android.
start()
method on Android uses android.os.Handler
, that do not run separate thread,
it doesn't return to React and make main execution to hang.
actualy i.m using expo cli to develop in react native but for use you native module i was need to use "expokit" because that is the way to use native modules in react native expo but i have the same mistake when i use expo cli than i use Expokit the issue is "special code undefined null is not an object (evaluating 'RNReactNativePing.start')" can you help me?
Just to make sure, is this intended behaviour?
2019-03-20 15:40:19.331 31167-31197/? W/System.err: java.lang.StringIndexOutOfBoundsException: length=0; index=18
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at java.lang.String.substring(String.java:1999)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at com.reactlibrary.PingUtil.getAvgRTT(Unknown Source:26)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at com.reactlibrary.PingUtil.getAvgRTT(Unknown Source:3)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at com.reactlibrary.RNReactNativePingModule.start(Unknown Source:17)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at com.facebook.react.bridge.JavaMethodWrapper.invoke(Unknown Source:148)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at com.facebook.react.bridge.JavaModuleWrapper.invoke(Unknown Source:21)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(Unknown Source:0)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at android.os.Looper.loop(Looper.java:193)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(Unknown Source:16)
2019-03-20 15:40:19.332 31167-31197/? W/System.err: at java.lang.Thread.run(Thread.java:764)
$ npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react-native
npm ERR! react-native@"0.73.6" from the root project
npm ERR! peer react-native@"*" from @gorhom/[email protected]
npm ERR! node_modules/@gorhom/bottom-sheet
npm ERR! @gorhom/bottom-sheet@"^4.6.1" from the root project
npm ERR! 40 more (@gorhom/portal, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react-native@"^0.41.2 || ^0.57.0 || ^0.68.0 || ^0.70.0" from [email protected]
npm ERR! node_modules/react-native-ping
npm ERR! react-native-ping@"^1.2.8" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/react-native
npm ERR! peer react-native@"^0.41.2 || ^0.57.0 || ^0.68.0 || ^0.70.0" from [email protected]
npm ERR! node_modules/react-native-ping
npm ERR! react-native-ping@"^1.2.8" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! /home/username/.npm/_logs/2024-03-25T20_10_19_693Z-eresolve-report.txt
npm ERR! A complete log of this run can be found in: /home/username/.npm/_logs/2024-03-25T20_10_19_693Z-debug-0.log
Error:Can't setup.The previous request is still running.
I have several local IP address to ping, if one down, others are down too.
new feature request:
await Ping.start('192.168.1.111', { timeout: 1500 })
error: package LHDefinition does not exist
LHDefinition.PING_ERROR_CODE error = LHDefinition.PING_ERROR_CODE.HostErrorNotSetHost;
Not sure if anyone is still maintaining this code anymore but I am having an issue when calling Ping.start with multiple IP addresses.
This is my current code utilizing this library. My code is as follows:
`async function checkIPAddressValid(fourthOctet) { //scanning the entire subnet on the fourth octect see if every ip address is alive
let ipSplit;
ipSplit = gatewayIPAddress.split('.');
const ipaddress = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2] + '.' + fourthOctet;
// const myModuleEvt = new NativeEventEmitter(NativeModules.MyModule)
await Ping.start(ipaddress, {timeout: 1000}).then((response) => {
if (ipaddress !== gatewayIPAddress && ipaddress !== deviceIPAddress) {
if (!ipList.includes(ipaddress)) {
ipList.push(ipaddress);
const defineResult = DoDefineAsync(ipaddress);
}
}
}).catch((error) => {
console.log(ipaddress: + ' ' + error + "\n");
});
}`
This particular function is called approximately 255 times. It is fairly immediately and "works" to get the IP addresses that I am looking for but it constantly throws an RCTFatal error and the following message.
"Illegal callback invocation from native module. This callback type only permits a single invocation from native code."
Any help solving this would be greatly appreciated. Thank you.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.