1.3.0 • Published 4 months ago

react-native-ping-android v1.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

react-native-ping-android

Expose the Internet Control Message Protocol (ICMP) to React Native android app.
Measure the round-trip time (RTT) by using ICMP echo request packets to the intended destination.

Installation

npm install react-native-ping-android

or with Yarn

yarn add react-native-ping-android

šŸš€ This library is supported in New Architecture (Turbo Modules)

APIs

ICMP

A bare JavaScript class to use ICMP controller

import { useRef } from 'react'
import { Button } from 'react-native'

import {
    ICMP,
    type ICMPResultInterface,
} from 'react-native-ping-android'

export default function App(): React.JSX.Element {
    const
        ref =
            useRef({
                icmp: new ICMP({ host: '1.1.1.1', packetSize: 64, timeout: 2000 }),
            }),

        [result, setResult] =
            useState<ICMPResultInterface | null>(null)

    const onPress = async () => {
        const { rtt, ttl, status } = await ref.current.icmp.ping()
        setResult({ rtt, ttl, status })
    }

    return (
        <Button
            title="Ping"
            onPress={ onPress } 
        />
    )
}

References

- Constructors: (data: ICMPConstructorDataInterface)

Data PropertiesTypeRequiredDefault ValueRemarks
hoststringYesvalid host, e.g. 1.1.1.1 or guthib.com. Invalid host or unknown service will return ping result with PingStatus.UNKNOWN_HOST status
packetSizenumber | null | undefinedNo56in bytes
timeoutnumber | null | undefinedNo1000in milliseconds
ttlnumber | null | undefinedNo54time-to-live

- Methods

MethodReturnRemarks
pingPromise<ICMPResultInterface>Run the ICMP ping with arguments that has been defined from constructor. This method will return with PingStatus.ECHOING status if the method is invoked again while the previous process is still running.
cancelvoidCancel current ICMP request. This method returns nothing. However the ping method which invoked before will return PingStatus.CANCELLED status. This method does nothing if there is no ICMP requests running.

- Properties

PropertyType
hostreadonly string
packetSizereadonly number
timeoutreadonly number
ttlreadonly number

- Static Members

Static MemberTypeValueRemarks
NO_ECHO_RTTnumber-1Just an constant whenever the status of ping result is not PingStatus.ECHO. It is used in the rtt result.
NO_ECHO_TTLnumber-1Just an constant whenever the status of ping result is not PingStatus.ECHO. It is used in the ttl result.

This API doesn't provide the count and interval functional arguments like in Windows/Darwin/Linux terminal.
If you want those, you can use the useICMP() React hook or you can implement your own interval and counter with this class. Feel free to create your own convinience.

It's safe to unmount the component without invoke the cancel method, like back to previous stack navigation, or unmount component with conditional rendering.

Good to hear that this module is using Kotlin Coroutines.

useICMP

A React hook of encapsulated ICMP class that you can use to simplify the ping handle with the count and the interval functional, since the ICMP class doesn't provide those arguments.

import { Button } from 'react-native'

import {
    useICMP,
} from 'react-native-ping-android'

export default function App(): React.JSX.Element {
    const { isRunning, result, start, stop } = useICMP()

    useEffect(() => {
        if(result) {
            console.log('Result: ', result.rtt, result.ttl, result.status)
        }
    }, [result])

    const toggle = () => {
        if(isRunning) {
            stop()
        } else {
            start({
                host: 'guthib.com',
                packetSize: 64,
                timeout: 1000,
                count: 10,
                interval: 1000,
            })
        }
    }

    return (
        <Button
            title={ isRunning ? 'Stop' : 'Start' }
            onPress={ toggle }
        />
    )
}

You can see full example at /example/src/screens/ping-runner/index.tsx

It's safe to unmount without invoke the stop method. This hook will cleanup the interval handler automatically.

Requirements
- Count must be larger than 0.
- Interval must be >= Timeout.

Otherwise, result will return with PingStatus.INVALID_ARG

References

- Returns: UseICMPInterface

PropertiesTypeRemarks
isRunningboolean
resultICMPResultInterfaceSee ICMPResultInterface
start(data: UseICMPStartParamsInterface) => voidSee UseICMPStartParamsInterface
stop() => void

isReachable

(host: string, timeout?: number) => Promise<boolean | null>

Simple function to test whether that address is reachable. Android implementation attempts ICMP ECHO REQUESTs first, on failure it will fall back to TCP ECHO REQUESTs. Success on either protocol will return true.

The host argument can either be a machine name, such as "guthib.com", or a textual representation of its IP address.
The timeout is 10000 (10 seconds) by default.

import { Button } from 'react-native'

import {
    isReachable,
} from 'react-native-ping-android'

export default function App(): React.JSX.Element {
    const onPress = async () => {
        const isReached = await isReachable('guthib.com')
        console.log('Is reached: ', isReached)
    }

    return (
        <Button
            title="Test"
            onPress={ onPress }
        />
    )
}

getHostName

(host: string) => Promise<string | null>

If the host argument was given with a host name, this host name will be remembered and returned; otherwise, a reverse name lookup will be performed and the result will be returned based on the system configured name lookup service.

Definitions

ICMPResultInterface

PropertiesTypeRemarks
rttnumberWhen the status is not PingStatus.ECHO, the value will be -1 (NO_ECHO_RTT)
ttlnumberWhen the status is not PingStatus.ECHO, the value will be -1 (NO_ECHO_TTL)
statusPingStatusFull references at PingStatus

ICMPConstructorDataInterface

PropertiesTypeRemarks
hoststringCan either be a machine name, such as "guthib.com", or a textual representation of its IP address.
packetSizenumber | null | undefinedValue in bytes. If it smaller than zero, the promise result will be returned with PingStatus.INVALID_ARG status.
ttlnumber | null | undefinedtime-to-live
timeoutnumber | null | undefinedValue in milliseconds.

UseICMPInterface

PropertiesTypeRemarks
isRunningbooleanA React state
resultICMPResultInterface | undefinedSee ICMPResultInterface
start(data: UseICMPStartParamsInterface) => voidSee UseICMPStartParamsInterface
stop() => voidStop the current running process. It does nothing when there is no processes.

UseICMPStartParamsInterface

It extends ICMPConstructorDataInterface | Properties | Type | Remarks | | ------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | count | number | Count must be larger than 0. Otherwise, the result will be returned with PingStatus.INVALID_ARG status | interval | number | Value in milliseconds and must be larger than 0 and larger than the timeout. Otherwise, the result will be returned with PingStatus.INVALID_ARG status | … | … | other props from ICMPConstructorDataInterface

PingStatus

MemberValueRemarks
ECHO2Success
ECHOING1When the ping method or start is invoked when the previous process still running
TIMEDOUT0
CANCELLED-1
UNKNOWN_HOST-2
INVALID_ARG-3Invalid argument such as illegal packet size, ttl out of range.
UNKNOWN_FAILURE-4

Android Emulator Limitations

Depending on the environment, the emulator might not be able to support other protocols (such as ICMP, used for "ping"). See Local networking limitations.

Instead, you can use Android physical device and run React Native app in it.

1.3.0

4 months ago

1.2.0

9 months ago

1.0.2

10 months ago

1.1.0

9 months ago

1.0.1

10 months ago

1.0.0

10 months ago

1.0.0-beta.2

10 months ago

1.0.0-beta.3

10 months ago

1.0.0-beta.4

10 months ago

1.0.3

10 months ago

1.0.0-beta.1

10 months ago

1.0.0-rc.3

10 months ago

1.0.0-rc.1

10 months ago

1.0.0-rc.2

10 months ago

0.0.1-prealpha.1

11 months ago