xref: /expo/packages/expo-network/src/Network.ts (revision 3d1dcea8)
1import { UnavailabilityError } from 'expo-modules-core';
2
3import ExpoNetwork from './ExpoNetwork';
4import { NetworkState, NetworkStateType } from './Network.types';
5
6export { NetworkState, NetworkStateType };
7
8// @needsAudit
9/**
10 * Gets the device's current network connection state.
11 *
12 * On web, `navigator.connection.type` is not available on browsers. So if there is an active
13 * network connection, the field `type` returns `NetworkStateType.UNKNOWN`. Otherwise, it returns
14 * `NetworkStateType.NONE`.
15 * @return A `Promise` that fulfils with a `NetworkState` object.
16 *
17 * @example
18 * ```ts
19 * await Network.getNetworkStateAsync();
20 * // {
21 * //   type: NetworkStateType.CELLULAR,
22 * //   isConnected: true,
23 * //   isInternetReachable: true,
24 * // }
25 * ```
26 */
27export async function getNetworkStateAsync(): Promise<NetworkState> {
28  if (!ExpoNetwork.getNetworkStateAsync) {
29    throw new UnavailabilityError('expo-network', 'getNetworkStateAsync');
30  }
31  return await ExpoNetwork.getNetworkStateAsync();
32}
33
34// @needsAudit
35/**
36 * Gets the device's current IPv4 address. Returns `0.0.0.0` if the IP address could not be retrieved.
37 *
38 * On web, this method uses the third-party [`ipify service`](https://www.ipify.org/) to get the
39 * public IP address of the current device.
40 * @return A `Promise` that fulfils with a `string` of the current IP address of the device's main
41 * network interface. Can only be IPv4 address.
42 *
43 * @example
44 * ```ts
45 * await Network.getIpAddressAsync();
46 * // "92.168.32.44"
47 * ```
48 */
49export async function getIpAddressAsync(): Promise<string> {
50  if (!ExpoNetwork.getIpAddressAsync) {
51    throw new UnavailabilityError('expo-network', 'getIpAddressAsync');
52  }
53  return await ExpoNetwork.getIpAddressAsync();
54}
55
56// @needsAudit
57/**
58 * Tells if the device is in airplane mode.
59 * @return Returns a `Promise` that fulfils with a `boolean` value for whether the device is in
60 * airplane mode or not.
61 * @platform android
62 *
63 * @example
64 * ```ts
65 * await Network.isAirplaneModeEnabledAsync();
66 * // false
67 * ```
68 */
69export async function isAirplaneModeEnabledAsync(): Promise<boolean> {
70  if (!ExpoNetwork.isAirplaneModeEnabledAsync) {
71    throw new UnavailabilityError('expo-network', 'isAirplaneModeEnabledAsync');
72  }
73  return await ExpoNetwork.isAirplaneModeEnabledAsync();
74}
75